	var __wxAppData = {}; 	var __wxRoute; 	var __wxRouteBegin; 	var global = {}; 		define("config.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

/**
 * 小程序配置文件
 */

var config = {};

module.exports = config; 
 			}); 		define("pages/order/order/oreder.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict"; 
 			}); 		define("utils/api.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

// const apiURL = 'https://testcps.hzins.com/trip';
var apiURL = 'https://www.qixin18.com/miniapp';
//const apiURL = 'http://127.0.0.1:3000';
var T = require("util");
var Q = require("q.js");

var wxRequest = function wxRequest(params, url) {
  params.data = params.data || {};
  params.data.sid = getApp().sid;
  if (params.showLoading) {
    T.showLoading();
  }
  wx.request({
    url: url,
    method: params.method || 'GET',
    data: params.data || {},
    header: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    success: function success(res) {
      if (params.success) {
        var data = T.clone(res.data) || {
          "code": -1
        };

        if (data.code === 10001) {
          getApp().clearSid();
          T.showTips(data.msg);
        } else if (data.code === 0) {
          params.success(data);
        } else {
          if (!params.autoTip) {
            T.showTips(data.msg || "请求失败，请重试");
          }

          if (params.fail) {
            params.fail(res);
          }
        }
      } else {
        if (params.fail) {
          params.fail(res);
        }
      }
    },
    fail: function fail(res) {
      if (params.fail) {
        params.fail(res);
      }
    },
    complete: function complete(res) {
      if (params.showLoading) {
        T.hideLoading();
      }
      if (params.complete) {
        params.complete(res);
      }
    }
  });
};

var sessionRequest = function sessionRequest(params, url) {
  getApp().checkSession().then(function () {
    wxRequest(params, url);
  });
};

var api = {
  apiURL: apiURL,
  jscode2session: function jscode2session(params) {
    wxRequest(params, apiURL + '/jscode2session/');
  },
  getTrial: function getTrial(params) {
    sessionRequest(params, apiURL + '/product/getTrial/');
  },
  tryTrial: function tryTrial(params) {
    sessionRequest(params, apiURL + '/product/tryTrial/');
  },
  insureAttr: function insureAttr(params) {
    sessionRequest(params, apiURL + '/product/insureAttr/');
  },
  trialInsuredPrice: function trialInsuredPrice(params) {
    sessionRequest(params, apiURL + '/product/trialInsuredPrice/');
  },
  saveInsure: function saveInsure(params) {
    sessionRequest(params, apiURL + '/insure/save/');
  },
  orderList: function orderList(params) {
    sessionRequest(params, apiURL + '/order/list/');
  },
  getOrderDetail: function getOrderDetail(params) {
    sessionRequest(params, apiURL + '/order/detail/');
  },
  getProductList: function getProductList(params) {
    sessionRequest(params, apiURL + '/product/list/');
  },
  paying: function paying(params) {
    sessionRequest(params, apiURL + '/pay/pay/');
  }
};

module.exports = api; 
 			}); 		define("utils/insure-config.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

var config = {
    renderConfg: {
        defaultTipMap: {
            cName: "请输入真实姓名",
            eName: "请输入英文名或名字拼音",
            cardNumber: "请输入有效证件号",
            moblie: "便于接收保单信息",
            email: "便于接收电子保单",
            cardOwner: "需为投保人本人",
            payAccount: "只支持储蓄卡",
            contactPost: "请输入",
            tel: "请输入有效电话",
            phone: "请输入有效电话",
            branchBank: "具体到分行支行",
            officeAddress: "输入详细地址便于联系和理赔",
            contactAddress: "输入详细地址便于联系和理赔",
            homeAddress: "输入详细地址便于联系和理赔",
            yearlyIncome: "输入数字类型年收入"
        },
        maxLengthMap: {
            cardNumber: 18,
            contactPost: 6,
            homePost: 6,
            officePost: 6,
            propertyPost: 6,
            moblie: 11,
            urgencyContactPhone: 11
        },
        inputTypeMap: {
            moblie: "number",
            height: "number",
            weight: "number",
            urgencyContactPhone: "number",
            propertyPost: "number",
            officePost: "number",
            contactPost: "number",
            homePost: "number",
            email: "text"
        }
    },
    tipMap: {
        cName: "请输入2-50位中文、4-50位英文"
        //contactAddress: "联系地址最少六位"
    },
    regMap: {},
    cardNumRegexJson: {
        2: { regex: /^[a-z0-9]*\d+[a-z0-9]*$/i, errorMsg: '护照格式错误' },
        5: { regex: /^(?!.*_)\w{8,}$/, errorMsg: '港澳通行证格式错误' },
        6: { regex: /^\d{4,20}$|^\w+字第\d{4,}$/, errorMsg: '军官证格式错误' },
        7: { regex: /^[A-Z0-9\(\)]{8,30}$/, errorMsg: '台胞证格式错误' },
        9: { regex: /^[A-Z0-9\(\)]{8,30}$/, errorMsg: '港澳台回乡证格式错误' },
        99: { regex: /^[\w \(\)-]{8,30}$/, errorMsg: '证号格式错误' }
    },
    cardTypeMap: [{ id: 1, value: '身份证' }, { id: 2, value: '护照' }, { id: 3, value: '出生证' }, { id: 4, value: '驾照' }, { id: 5, value: '港澳通行证' }, { id: 6, value: '军官证' }, { id: 99, value: '其他' }, { id: 7, value: '台胞证' }, { id: 8, value: '警官证' }, { id: 9, value: '港澳台回乡证' }, { id: 10, value: '组织机构代码证' }, { id: 11, value: '营业执照' }, { id: 12, value: '税务登记号' }, { id: 13, value: '三证合一' }, { id: 14, value: '统一信用代码证' }]

};

module.exports = config; 
 			}); 		define("utils/moment.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

//! moment.js
//! version : 2.17.1
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com

;(function (global, factory) {
    (typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.moment = factory();
})(undefined, function () {
    'use strict';

    var hookCallback;

    function hooks() {
        return hookCallback.apply(null, arguments);
    }

    // This is done to register the method called with moment()
    // without creating circular dependencies.
    function setHookCallback(callback) {
        hookCallback = callback;
    }

    function isArray(input) {
        return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
    }

    function isObject(input) {
        // IE8 will treat undefined and null as object if it wasn't for
        // input != null
        return input != null && Object.prototype.toString.call(input) === '[object Object]';
    }

    function isObjectEmpty(obj) {
        var k;
        for (k in obj) {
            // even if its not own property I'd still call it non-empty
            return false;
        }
        return true;
    }

    function isNumber(input) {
        return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
    }

    function isDate(input) {
        return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
    }

    function map(arr, fn) {
        var res = [],
            i;
        for (i = 0; i < arr.length; ++i) {
            res.push(fn(arr[i], i));
        }
        return res;
    }

    function hasOwnProp(a, b) {
        return Object.prototype.hasOwnProperty.call(a, b);
    }

    function extend(a, b) {
        for (var i in b) {
            if (hasOwnProp(b, i)) {
                a[i] = b[i];
            }
        }

        if (hasOwnProp(b, 'toString')) {
            a.toString = b.toString;
        }

        if (hasOwnProp(b, 'valueOf')) {
            a.valueOf = b.valueOf;
        }

        return a;
    }

    function createUTC(input, format, locale, strict) {
        return createLocalOrUTC(input, format, locale, strict, true).utc();
    }

    function defaultParsingFlags() {
        // We need to deep clone this object.
        return {
            empty: false,
            unusedTokens: [],
            unusedInput: [],
            overflow: -2,
            charsLeftOver: 0,
            nullInput: false,
            invalidMonth: null,
            invalidFormat: false,
            userInvalidated: false,
            iso: false,
            parsedDateParts: [],
            meridiem: null
        };
    }

    function getParsingFlags(m) {
        if (m._pf == null) {
            m._pf = defaultParsingFlags();
        }
        return m._pf;
    }

    var some;
    if (Array.prototype.some) {
        some = Array.prototype.some;
    } else {
        some = function some(fun) {
            var t = Object(this);
            var len = t.length >>> 0;

            for (var i = 0; i < len; i++) {
                if (i in t && fun.call(this, t[i], i, t)) {
                    return true;
                }
            }

            return false;
        };
    }

    var some$1 = some;

    function isValid(m) {
        if (m._isValid == null) {
            var flags = getParsingFlags(m);
            var parsedParts = some$1.call(flags.parsedDateParts, function (i) {
                return i != null;
            });
            var isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidMonth && !flags.invalidWeekday && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts);

            if (m._strict) {
                isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined;
            }

            if (Object.isFrozen == null || !Object.isFrozen(m)) {
                m._isValid = isNowValid;
            } else {
                return isNowValid;
            }
        }
        return m._isValid;
    }

    function createInvalid(flags) {
        var m = createUTC(NaN);
        if (flags != null) {
            extend(getParsingFlags(m), flags);
        } else {
            getParsingFlags(m).userInvalidated = true;
        }

        return m;
    }

    function isUndefined(input) {
        return input === void 0;
    }

    // Plugins that add properties should also add the key here (null value),
    // so we can properly clone ourselves.
    var momentProperties = hooks.momentProperties = [];

    function copyConfig(to, from) {
        var i, prop, val;

        if (!isUndefined(from._isAMomentObject)) {
            to._isAMomentObject = from._isAMomentObject;
        }
        if (!isUndefined(from._i)) {
            to._i = from._i;
        }
        if (!isUndefined(from._f)) {
            to._f = from._f;
        }
        if (!isUndefined(from._l)) {
            to._l = from._l;
        }
        if (!isUndefined(from._strict)) {
            to._strict = from._strict;
        }
        if (!isUndefined(from._tzm)) {
            to._tzm = from._tzm;
        }
        if (!isUndefined(from._isUTC)) {
            to._isUTC = from._isUTC;
        }
        if (!isUndefined(from._offset)) {
            to._offset = from._offset;
        }
        if (!isUndefined(from._pf)) {
            to._pf = getParsingFlags(from);
        }
        if (!isUndefined(from._locale)) {
            to._locale = from._locale;
        }

        if (momentProperties.length > 0) {
            for (i in momentProperties) {
                prop = momentProperties[i];
                val = from[prop];
                if (!isUndefined(val)) {
                    to[prop] = val;
                }
            }
        }

        return to;
    }

    var updateInProgress = false;

    // Moment prototype object
    function Moment(config) {
        copyConfig(this, config);
        this._d = new Date(config._d != null ? config._d.getTime() : NaN);
        if (!this.isValid()) {
            this._d = new Date(NaN);
        }
        // Prevent infinite loop in case updateOffset creates new moment
        // objects.
        if (updateInProgress === false) {
            updateInProgress = true;
            hooks.updateOffset(this);
            updateInProgress = false;
        }
    }

    function isMoment(obj) {
        return obj instanceof Moment || obj != null && obj._isAMomentObject != null;
    }

    function absFloor(number) {
        if (number < 0) {
            // -0 -> 0
            return Math.ceil(number) || 0;
        } else {
            return Math.floor(number);
        }
    }

    function toInt(argumentForCoercion) {
        var coercedNumber = +argumentForCoercion,
            value = 0;

        if (coercedNumber !== 0 && isFinite(coercedNumber)) {
            value = absFloor(coercedNumber);
        }

        return value;
    }

    // compare two arrays, return the number of differences
    function compareArrays(array1, array2, dontConvert) {
        var len = Math.min(array1.length, array2.length),
            lengthDiff = Math.abs(array1.length - array2.length),
            diffs = 0,
            i;
        for (i = 0; i < len; i++) {
            if (dontConvert && array1[i] !== array2[i] || !dontConvert && toInt(array1[i]) !== toInt(array2[i])) {
                diffs++;
            }
        }
        return diffs + lengthDiff;
    }

    function warn(msg) {
        if (hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) {
            console.warn('Deprecation warning: ' + msg);
        }
    }

    function deprecate(msg, fn) {
        var firstTime = true;

        return extend(function () {
            if (hooks.deprecationHandler != null) {
                hooks.deprecationHandler(null, msg);
            }
            if (firstTime) {
                var args = [];
                var arg;
                for (var i = 0; i < arguments.length; i++) {
                    arg = '';
                    if (_typeof(arguments[i]) === 'object') {
                        arg += '\n[' + i + '] ';
                        for (var key in arguments[0]) {
                            arg += key + ': ' + arguments[0][key] + ', ';
                        }
                        arg = arg.slice(0, -2); // Remove trailing comma and space
                    } else {
                        arg = arguments[i];
                    }
                    args.push(arg);
                }
                warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + new Error().stack);
                firstTime = false;
            }
            return fn.apply(this, arguments);
        }, fn);
    }

    var deprecations = {};

    function deprecateSimple(name, msg) {
        if (hooks.deprecationHandler != null) {
            hooks.deprecationHandler(name, msg);
        }
        if (!deprecations[name]) {
            warn(msg);
            deprecations[name] = true;
        }
    }

    hooks.suppressDeprecationWarnings = false;
    hooks.deprecationHandler = null;

    function isFunction(input) {
        return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
    }

    function set(config) {
        var prop, i;
        for (i in config) {
            prop = config[i];
            if (isFunction(prop)) {
                this[i] = prop;
            } else {
                this['_' + i] = prop;
            }
        }
        this._config = config;
        // Lenient ordinal parsing accepts just a number in addition to
        // number + (possibly) stuff coming from _ordinalParseLenient.
        this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + /\d{1,2}/.source);
    }

    function mergeConfigs(parentConfig, childConfig) {
        var res = extend({}, parentConfig),
            prop;
        for (prop in childConfig) {
            if (hasOwnProp(childConfig, prop)) {
                if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
                    res[prop] = {};
                    extend(res[prop], parentConfig[prop]);
                    extend(res[prop], childConfig[prop]);
                } else if (childConfig[prop] != null) {
                    res[prop] = childConfig[prop];
                } else {
                    delete res[prop];
                }
            }
        }
        for (prop in parentConfig) {
            if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop])) {
                // make sure changes to properties don't modify parent config
                res[prop] = extend({}, res[prop]);
            }
        }
        return res;
    }

    function Locale(config) {
        if (config != null) {
            this.set(config);
        }
    }

    var keys;

    if (Object.keys) {
        keys = Object.keys;
    } else {
        keys = function keys(obj) {
            var i,
                res = [];
            for (i in obj) {
                if (hasOwnProp(obj, i)) {
                    res.push(i);
                }
            }
            return res;
        };
    }

    var keys$1 = keys;

    var defaultCalendar = {
        sameDay: '[Today at] LT',
        nextDay: '[Tomorrow at] LT',
        nextWeek: 'dddd [at] LT',
        lastDay: '[Yesterday at] LT',
        lastWeek: '[Last] dddd [at] LT',
        sameElse: 'L'
    };

    function calendar(key, mom, now) {
        var output = this._calendar[key] || this._calendar['sameElse'];
        return isFunction(output) ? output.call(mom, now) : output;
    }

    var defaultLongDateFormat = {
        LTS: 'h:mm:ss A',
        LT: 'h:mm A',
        L: 'MM/DD/YYYY',
        LL: 'MMMM D, YYYY',
        LLL: 'MMMM D, YYYY h:mm A',
        LLLL: 'dddd, MMMM D, YYYY h:mm A'
    };

    function longDateFormat(key) {
        var format = this._longDateFormat[key],
            formatUpper = this._longDateFormat[key.toUpperCase()];

        if (format || !formatUpper) {
            return format;
        }

        this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
            return val.slice(1);
        });

        return this._longDateFormat[key];
    }

    var defaultInvalidDate = 'Invalid date';

    function invalidDate() {
        return this._invalidDate;
    }

    var defaultOrdinal = '%d';
    var defaultOrdinalParse = /\d{1,2}/;

    function ordinal(number) {
        return this._ordinal.replace('%d', number);
    }

    var defaultRelativeTime = {
        future: 'in %s',
        past: '%s ago',
        s: 'a few seconds',
        m: 'a minute',
        mm: '%d minutes',
        h: 'an hour',
        hh: '%d hours',
        d: 'a day',
        dd: '%d days',
        M: 'a month',
        MM: '%d months',
        y: 'a year',
        yy: '%d years'
    };

    function relativeTime(number, withoutSuffix, string, isFuture) {
        var output = this._relativeTime[string];
        return isFunction(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number);
    }

    function pastFuture(diff, output) {
        var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
        return isFunction(format) ? format(output) : format.replace(/%s/i, output);
    }

    var aliases = {};

    function addUnitAlias(unit, shorthand) {
        var lowerCase = unit.toLowerCase();
        aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
    }

    function normalizeUnits(units) {
        return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
    }

    function normalizeObjectUnits(inputObject) {
        var normalizedInput = {},
            normalizedProp,
            prop;

        for (prop in inputObject) {
            if (hasOwnProp(inputObject, prop)) {
                normalizedProp = normalizeUnits(prop);
                if (normalizedProp) {
                    normalizedInput[normalizedProp] = inputObject[prop];
                }
            }
        }

        return normalizedInput;
    }

    var priorities = {};

    function addUnitPriority(unit, priority) {
        priorities[unit] = priority;
    }

    function getPrioritizedUnits(unitsObj) {
        var units = [];
        for (var u in unitsObj) {
            units.push({ unit: u, priority: priorities[u] });
        }
        units.sort(function (a, b) {
            return a.priority - b.priority;
        });
        return units;
    }

    function makeGetSet(unit, keepTime) {
        return function (value) {
            if (value != null) {
                set$1(this, unit, value);
                hooks.updateOffset(this, keepTime);
                return this;
            } else {
                return get(this, unit);
            }
        };
    }

    function get(mom, unit) {
        return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
    }

    function set$1(mom, unit, value) {
        if (mom.isValid()) {
            mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
        }
    }

    // MOMENTS

    function stringGet(units) {
        units = normalizeUnits(units);
        if (isFunction(this[units])) {
            return this[units]();
        }
        return this;
    }

    function stringSet(units, value) {
        if ((typeof units === 'undefined' ? 'undefined' : _typeof(units)) === 'object') {
            units = normalizeObjectUnits(units);
            var prioritized = getPrioritizedUnits(units);
            for (var i = 0; i < prioritized.length; i++) {
                this[prioritized[i].unit](units[prioritized[i].unit]);
            }
        } else {
            units = normalizeUnits(units);
            if (isFunction(this[units])) {
                return this[units](value);
            }
        }
        return this;
    }

    function zeroFill(number, targetLength, forceSign) {
        var absNumber = '' + Math.abs(number),
            zerosToFill = targetLength - absNumber.length,
            sign = number >= 0;
        return (sign ? forceSign ? '+' : '' : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
    }

    var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;

    var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;

    var formatFunctions = {};

    var formatTokenFunctions = {};

    // token:    'M'
    // padded:   ['MM', 2]
    // ordinal:  'Mo'
    // callback: function () { this.month() + 1 }
    function addFormatToken(token, padded, ordinal, callback) {
        var func = callback;
        if (typeof callback === 'string') {
            func = function func() {
                return this[callback]();
            };
        }
        if (token) {
            formatTokenFunctions[token] = func;
        }
        if (padded) {
            formatTokenFunctions[padded[0]] = function () {
                return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
            };
        }
        if (ordinal) {
            formatTokenFunctions[ordinal] = function () {
                return this.localeData().ordinal(func.apply(this, arguments), token);
            };
        }
    }

    function removeFormattingTokens(input) {
        if (input.match(/\[[\s\S]/)) {
            return input.replace(/^\[|\]$/g, '');
        }
        return input.replace(/\\/g, '');
    }

    function makeFormatFunction(format) {
        var array = format.match(formattingTokens),
            i,
            length;

        for (i = 0, length = array.length; i < length; i++) {
            if (formatTokenFunctions[array[i]]) {
                array[i] = formatTokenFunctions[array[i]];
            } else {
                array[i] = removeFormattingTokens(array[i]);
            }
        }

        return function (mom) {
            var output = '',
                i;
            for (i = 0; i < length; i++) {
                /*** we
                output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
                we ***/

                /*** we ***/
                output += typeof array[i] == "function" ? array[i].call(mom, format) : array[i];
                /*** we ***/
            }
            return output;
        };
    }

    // format date using native date object
    function formatMoment(m, format) {
        if (!m.isValid()) {
            return m.localeData().invalidDate();
        }

        format = expandFormat(format, m.localeData());
        formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);

        return formatFunctions[format](m);
    }

    function expandFormat(format, locale) {
        var i = 5;

        function replaceLongDateFormatTokens(input) {
            return locale.longDateFormat(input) || input;
        }

        localFormattingTokens.lastIndex = 0;
        while (i >= 0 && localFormattingTokens.test(format)) {
            format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
            localFormattingTokens.lastIndex = 0;
            i -= 1;
        }

        return format;
    }

    var match1 = /\d/; //       0 - 9
    var match2 = /\d\d/; //      00 - 99
    var match3 = /\d{3}/; //     000 - 999
    var match4 = /\d{4}/; //    0000 - 9999
    var match6 = /[+-]?\d{6}/; // -999999 - 999999
    var match1to2 = /\d\d?/; //       0 - 99
    var match3to4 = /\d\d\d\d?/; //     999 - 9999
    var match5to6 = /\d\d\d\d\d\d?/; //   99999 - 999999
    var match1to3 = /\d{1,3}/; //       0 - 999
    var match1to4 = /\d{1,4}/; //       0 - 9999
    var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999

    var matchUnsigned = /\d+/; //       0 - inf
    var matchSigned = /[+-]?\d+/; //    -inf - inf

    var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
    var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z

    var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123

    // any word (or two) characters or numbers including two/three word month in arabic.
    // includes scottish gaelic two word and hyphenated months
    var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;

    var regexes = {};

    function addRegexToken(token, regex, strictRegex) {
        regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
            return isStrict && strictRegex ? strictRegex : regex;
        };
    }

    function getParseRegexForToken(token, config) {
        if (!hasOwnProp(regexes, token)) {
            return new RegExp(unescapeFormat(token));
        }

        return regexes[token](config._strict, config._locale);
    }

    // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
    function unescapeFormat(s) {
        return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
            return p1 || p2 || p3 || p4;
        }));
    }

    function regexEscape(s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }

    var tokens = {};

    function addParseToken(token, callback) {
        var i,
            func = callback;
        if (typeof token === 'string') {
            token = [token];
        }
        if (isNumber(callback)) {
            func = function func(input, array) {
                array[callback] = toInt(input);
            };
        }
        for (i = 0; i < token.length; i++) {
            tokens[token[i]] = func;
        }
    }

    function addWeekParseToken(token, callback) {
        addParseToken(token, function (input, array, config, token) {
            config._w = config._w || {};
            callback(input, config._w, config, token);
        });
    }

    function addTimeToArrayFromToken(token, input, config) {
        if (input != null && hasOwnProp(tokens, token)) {
            tokens[token](input, config._a, config, token);
        }
    }

    var YEAR = 0;
    var MONTH = 1;
    var DATE = 2;
    var HOUR = 3;
    var MINUTE = 4;
    var SECOND = 5;
    var MILLISECOND = 6;
    var WEEK = 7;
    var WEEKDAY = 8;

    var indexOf;

    if (Array.prototype.indexOf) {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function indexOf(o) {
            // I know
            var i;
            for (i = 0; i < this.length; ++i) {
                if (this[i] === o) {
                    return i;
                }
            }
            return -1;
        };
    }

    var indexOf$1 = indexOf;

    function daysInMonth(year, month) {
        return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
    }

    // FORMATTING

    addFormatToken('M', ['MM', 2], 'Mo', function () {
        return this.month() + 1;
    });

    addFormatToken('MMM', 0, 0, function (format) {
        return this.localeData().monthsShort(this, format);
    });

    addFormatToken('MMMM', 0, 0, function (format) {
        return this.localeData().months(this, format);
    });

    // ALIASES

    addUnitAlias('month', 'M');

    // PRIORITY

    addUnitPriority('month', 8);

    // PARSING

    addRegexToken('M', match1to2);
    addRegexToken('MM', match1to2, match2);
    addRegexToken('MMM', function (isStrict, locale) {
        return locale.monthsShortRegex(isStrict);
    });
    addRegexToken('MMMM', function (isStrict, locale) {
        return locale.monthsRegex(isStrict);
    });

    addParseToken(['M', 'MM'], function (input, array) {
        array[MONTH] = toInt(input) - 1;
    });

    addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
        var month = config._locale.monthsParse(input, token, config._strict);
        // if we didn't find a month name, mark the date as invalid.
        if (month != null) {
            array[MONTH] = month;
        } else {
            getParsingFlags(config).invalidMonth = input;
        }
    });

    // LOCALES

    var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
    var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
    function localeMonths(m, format) {
        if (!m) {
            return this._months;
        }
        return isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
    }

    var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
    function localeMonthsShort(m, format) {
        if (!m) {
            return this._monthsShort;
        }
        return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
    }

    function handleStrictParse(monthName, format, strict) {
        var i,
            ii,
            mom,
            llc = monthName.toLocaleLowerCase();
        if (!this._monthsParse) {
            // this is not used
            this._monthsParse = [];
            this._longMonthsParse = [];
            this._shortMonthsParse = [];
            for (i = 0; i < 12; ++i) {
                mom = createUTC([2000, i]);
                this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
                this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
            }
        }

        if (strict) {
            if (format === 'MMM') {
                ii = indexOf$1.call(this._shortMonthsParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf$1.call(this._longMonthsParse, llc);
                return ii !== -1 ? ii : null;
            }
        } else {
            if (format === 'MMM') {
                ii = indexOf$1.call(this._shortMonthsParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._longMonthsParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf$1.call(this._longMonthsParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._shortMonthsParse, llc);
                return ii !== -1 ? ii : null;
            }
        }
    }

    function localeMonthsParse(monthName, format, strict) {
        var i, mom, regex;

        if (this._monthsParseExact) {
            return handleStrictParse.call(this, monthName, format, strict);
        }

        if (!this._monthsParse) {
            this._monthsParse = [];
            this._longMonthsParse = [];
            this._shortMonthsParse = [];
        }

        // TODO: add sorting
        // Sorting makes sure if one month (or abbr) is a prefix of another
        // see sorting in computeMonthsParse
        for (i = 0; i < 12; i++) {
            // make the regex if we don't have it already
            mom = createUTC([2000, i]);
            if (strict && !this._longMonthsParse[i]) {
                this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
                this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
            }
            if (!strict && !this._monthsParse[i]) {
                regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
                this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
            }
            // test the regex
            if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
                return i;
            } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
                return i;
            } else if (!strict && this._monthsParse[i].test(monthName)) {
                return i;
            }
        }
    }

    // MOMENTS

    function setMonth(mom, value) {
        var dayOfMonth;

        if (!mom.isValid()) {
            // No op
            return mom;
        }

        if (typeof value === 'string') {
            if (/^\d+$/.test(value)) {
                value = toInt(value);
            } else {
                value = mom.localeData().monthsParse(value);
                // TODO: Another silent failure?
                if (!isNumber(value)) {
                    return mom;
                }
            }
        }

        dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
        mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
        return mom;
    }

    function getSetMonth(value) {
        if (value != null) {
            setMonth(this, value);
            hooks.updateOffset(this, true);
            return this;
        } else {
            return get(this, 'Month');
        }
    }

    function getDaysInMonth() {
        return daysInMonth(this.year(), this.month());
    }

    var defaultMonthsShortRegex = matchWord;
    function monthsShortRegex(isStrict) {
        if (this._monthsParseExact) {
            if (!hasOwnProp(this, '_monthsRegex')) {
                computeMonthsParse.call(this);
            }
            if (isStrict) {
                return this._monthsShortStrictRegex;
            } else {
                return this._monthsShortRegex;
            }
        } else {
            if (!hasOwnProp(this, '_monthsShortRegex')) {
                this._monthsShortRegex = defaultMonthsShortRegex;
            }
            return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex;
        }
    }

    var defaultMonthsRegex = matchWord;
    function monthsRegex(isStrict) {
        if (this._monthsParseExact) {
            if (!hasOwnProp(this, '_monthsRegex')) {
                computeMonthsParse.call(this);
            }
            if (isStrict) {
                return this._monthsStrictRegex;
            } else {
                return this._monthsRegex;
            }
        } else {
            if (!hasOwnProp(this, '_monthsRegex')) {
                this._monthsRegex = defaultMonthsRegex;
            }
            return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex;
        }
    }

    function computeMonthsParse() {
        function cmpLenRev(a, b) {
            return b.length - a.length;
        }

        var shortPieces = [],
            longPieces = [],
            mixedPieces = [],
            i,
            mom;
        for (i = 0; i < 12; i++) {
            // make the regex if we don't have it already
            mom = createUTC([2000, i]);
            shortPieces.push(this.monthsShort(mom, ''));
            longPieces.push(this.months(mom, ''));
            mixedPieces.push(this.months(mom, ''));
            mixedPieces.push(this.monthsShort(mom, ''));
        }
        // Sorting makes sure if one month (or abbr) is a prefix of another it
        // will match the longer piece.
        shortPieces.sort(cmpLenRev);
        longPieces.sort(cmpLenRev);
        mixedPieces.sort(cmpLenRev);
        for (i = 0; i < 12; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
        }
        for (i = 0; i < 24; i++) {
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }

        this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
        this._monthsShortRegex = this._monthsRegex;
        this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
        this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
    }

    // FORMATTING

    addFormatToken('Y', 0, 0, function () {
        var y = this.year();
        return y <= 9999 ? '' + y : '+' + y;
    });

    addFormatToken(0, ['YY', 2], 0, function () {
        return this.year() % 100;
    });

    addFormatToken(0, ['YYYY', 4], 0, 'year');
    addFormatToken(0, ['YYYYY', 5], 0, 'year');
    addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');

    // ALIASES

    addUnitAlias('year', 'y');

    // PRIORITIES

    addUnitPriority('year', 1);

    // PARSING

    addRegexToken('Y', matchSigned);
    addRegexToken('YY', match1to2, match2);
    addRegexToken('YYYY', match1to4, match4);
    addRegexToken('YYYYY', match1to6, match6);
    addRegexToken('YYYYYY', match1to6, match6);

    addParseToken(['YYYYY', 'YYYYYY'], YEAR);
    addParseToken('YYYY', function (input, array) {
        array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
    });
    addParseToken('YY', function (input, array) {
        array[YEAR] = hooks.parseTwoDigitYear(input);
    });
    addParseToken('Y', function (input, array) {
        array[YEAR] = parseInt(input, 10);
    });

    // HELPERS

    function daysInYear(year) {
        return isLeapYear(year) ? 366 : 365;
    }

    function isLeapYear(year) {
        return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
    }

    // HOOKS

    hooks.parseTwoDigitYear = function (input) {
        return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
    };

    // MOMENTS

    var getSetYear = makeGetSet('FullYear', true);

    function getIsLeapYear() {
        return isLeapYear(this.year());
    }

    function createDate(y, m, d, h, M, s, ms) {
        //can't just apply() to create a date:
        //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
        var date = new Date(y, m, d, h, M, s, ms);

        //the date constructor remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
            date.setFullYear(y);
        }
        return date;
    }

    function createUTCDate(y) {
        var date = new Date(Date.UTC.apply(null, arguments));

        //the Date.UTC function remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
            date.setUTCFullYear(y);
        }
        return date;
    }

    // start-of-first-week - start-of-year
    function firstWeekOffset(year, dow, doy) {
        var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
        fwd = 7 + dow - doy,

        // first-week day local weekday -- which local weekday is fwd
        fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;

        return -fwdlw + fwd - 1;
    }

    //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
    function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
        var localWeekday = (7 + weekday - dow) % 7,
            weekOffset = firstWeekOffset(year, dow, doy),
            dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
            resYear,
            resDayOfYear;

        if (dayOfYear <= 0) {
            resYear = year - 1;
            resDayOfYear = daysInYear(resYear) + dayOfYear;
        } else if (dayOfYear > daysInYear(year)) {
            resYear = year + 1;
            resDayOfYear = dayOfYear - daysInYear(year);
        } else {
            resYear = year;
            resDayOfYear = dayOfYear;
        }

        return {
            year: resYear,
            dayOfYear: resDayOfYear
        };
    }

    function weekOfYear(mom, dow, doy) {
        var weekOffset = firstWeekOffset(mom.year(), dow, doy),
            week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
            resWeek,
            resYear;

        if (week < 1) {
            resYear = mom.year() - 1;
            resWeek = week + weeksInYear(resYear, dow, doy);
        } else if (week > weeksInYear(mom.year(), dow, doy)) {
            resWeek = week - weeksInYear(mom.year(), dow, doy);
            resYear = mom.year() + 1;
        } else {
            resYear = mom.year();
            resWeek = week;
        }

        return {
            week: resWeek,
            year: resYear
        };
    }

    function weeksInYear(year, dow, doy) {
        var weekOffset = firstWeekOffset(year, dow, doy),
            weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
        return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
    }

    // FORMATTING

    addFormatToken('w', ['ww', 2], 'wo', 'week');
    addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');

    // ALIASES

    addUnitAlias('week', 'w');
    addUnitAlias('isoWeek', 'W');

    // PRIORITIES

    addUnitPriority('week', 5);
    addUnitPriority('isoWeek', 5);

    // PARSING

    addRegexToken('w', match1to2);
    addRegexToken('ww', match1to2, match2);
    addRegexToken('W', match1to2);
    addRegexToken('WW', match1to2, match2);

    addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
        week[token.substr(0, 1)] = toInt(input);
    });

    // HELPERS

    // LOCALES

    function localeWeek(mom) {
        return weekOfYear(mom, this._week.dow, this._week.doy).week;
    }

    var defaultLocaleWeek = {
        dow: 0, // Sunday is the first day of the week.
        doy: 6 // The week that contains Jan 1st is the first week of the year.
    };

    function localeFirstDayOfWeek() {
        return this._week.dow;
    }

    function localeFirstDayOfYear() {
        return this._week.doy;
    }

    // MOMENTS

    function getSetWeek(input) {
        var week = this.localeData().week(this);
        return input == null ? week : this.add((input - week) * 7, 'd');
    }

    function getSetISOWeek(input) {
        var week = weekOfYear(this, 1, 4).week;
        return input == null ? week : this.add((input - week) * 7, 'd');
    }

    // FORMATTING

    addFormatToken('d', 0, 'do', 'day');

    addFormatToken('dd', 0, 0, function (format) {
        return this.localeData().weekdaysMin(this, format);
    });

    addFormatToken('ddd', 0, 0, function (format) {
        return this.localeData().weekdaysShort(this, format);
    });

    addFormatToken('dddd', 0, 0, function (format) {
        return this.localeData().weekdays(this, format);
    });

    addFormatToken('e', 0, 0, 'weekday');
    addFormatToken('E', 0, 0, 'isoWeekday');

    // ALIASES

    addUnitAlias('day', 'd');
    addUnitAlias('weekday', 'e');
    addUnitAlias('isoWeekday', 'E');

    // PRIORITY
    addUnitPriority('day', 11);
    addUnitPriority('weekday', 11);
    addUnitPriority('isoWeekday', 11);

    // PARSING

    addRegexToken('d', match1to2);
    addRegexToken('e', match1to2);
    addRegexToken('E', match1to2);
    addRegexToken('dd', function (isStrict, locale) {
        return locale.weekdaysMinRegex(isStrict);
    });
    addRegexToken('ddd', function (isStrict, locale) {
        return locale.weekdaysShortRegex(isStrict);
    });
    addRegexToken('dddd', function (isStrict, locale) {
        return locale.weekdaysRegex(isStrict);
    });

    addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
        var weekday = config._locale.weekdaysParse(input, token, config._strict);
        // if we didn't get a weekday name, mark the date as invalid
        if (weekday != null) {
            week.d = weekday;
        } else {
            getParsingFlags(config).invalidWeekday = input;
        }
    });

    addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
        week[token] = toInt(input);
    });

    // HELPERS

    function parseWeekday(input, locale) {
        if (typeof input !== 'string') {
            return input;
        }

        if (!isNaN(input)) {
            return parseInt(input, 10);
        }

        input = locale.weekdaysParse(input);
        if (typeof input === 'number') {
            return input;
        }

        return null;
    }

    function parseIsoWeekday(input, locale) {
        if (typeof input === 'string') {
            return locale.weekdaysParse(input) % 7 || 7;
        }
        return isNaN(input) ? null : input;
    }

    // LOCALES

    var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
    function localeWeekdays(m, format) {
        if (!m) {
            return this._weekdays;
        }
        return isArray(this._weekdays) ? this._weekdays[m.day()] : this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
    }

    var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
    function localeWeekdaysShort(m) {
        return m ? this._weekdaysShort[m.day()] : this._weekdaysShort;
    }

    var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
    function localeWeekdaysMin(m) {
        return m ? this._weekdaysMin[m.day()] : this._weekdaysMin;
    }

    function handleStrictParse$1(weekdayName, format, strict) {
        var i,
            ii,
            mom,
            llc = weekdayName.toLocaleLowerCase();
        if (!this._weekdaysParse) {
            this._weekdaysParse = [];
            this._shortWeekdaysParse = [];
            this._minWeekdaysParse = [];

            for (i = 0; i < 7; ++i) {
                mom = createUTC([2000, 1]).day(i);
                this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
                this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
                this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
            }
        }

        if (strict) {
            if (format === 'dddd') {
                ii = indexOf$1.call(this._weekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else if (format === 'ddd') {
                ii = indexOf$1.call(this._shortWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf$1.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            }
        } else {
            if (format === 'dddd') {
                ii = indexOf$1.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._shortWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else if (format === 'ddd') {
                ii = indexOf$1.call(this._shortWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf$1.call(this._minWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._shortWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            }
        }
    }

    function localeWeekdaysParse(weekdayName, format, strict) {
        var i, mom, regex;

        if (this._weekdaysParseExact) {
            return handleStrictParse$1.call(this, weekdayName, format, strict);
        }

        if (!this._weekdaysParse) {
            this._weekdaysParse = [];
            this._minWeekdaysParse = [];
            this._shortWeekdaysParse = [];
            this._fullWeekdaysParse = [];
        }

        for (i = 0; i < 7; i++) {
            // make the regex if we don't have it already

            mom = createUTC([2000, 1]).day(i);
            if (strict && !this._fullWeekdaysParse[i]) {
                this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
                this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
                this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
            }
            if (!this._weekdaysParse[i]) {
                regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
                this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
            }
            // test the regex
            if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
                return i;
            }
        }
    }

    // MOMENTS

    function getSetDayOfWeek(input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
        if (input != null) {
            input = parseWeekday(input, this.localeData());
            return this.add(input - day, 'd');
        } else {
            return day;
        }
    }

    function getSetLocaleDayOfWeek(input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
        return input == null ? weekday : this.add(input - weekday, 'd');
    }

    function getSetISODayOfWeek(input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }

        // behaves the same as moment#day except
        // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
        // as a setter, sunday should belong to the previous week.

        if (input != null) {
            var weekday = parseIsoWeekday(input, this.localeData());
            return this.day(this.day() % 7 ? weekday : weekday - 7);
        } else {
            return this.day() || 7;
        }
    }

    var defaultWeekdaysRegex = matchWord;
    function weekdaysRegex(isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysStrictRegex;
            } else {
                return this._weekdaysRegex;
            }
        } else {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                this._weekdaysRegex = defaultWeekdaysRegex;
            }
            return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex;
        }
    }

    var defaultWeekdaysShortRegex = matchWord;
    function weekdaysShortRegex(isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysShortStrictRegex;
            } else {
                return this._weekdaysShortRegex;
            }
        } else {
            if (!hasOwnProp(this, '_weekdaysShortRegex')) {
                this._weekdaysShortRegex = defaultWeekdaysShortRegex;
            }
            return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
        }
    }

    var defaultWeekdaysMinRegex = matchWord;
    function weekdaysMinRegex(isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysMinStrictRegex;
            } else {
                return this._weekdaysMinRegex;
            }
        } else {
            if (!hasOwnProp(this, '_weekdaysMinRegex')) {
                this._weekdaysMinRegex = defaultWeekdaysMinRegex;
            }
            return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
        }
    }

    function computeWeekdaysParse() {
        function cmpLenRev(a, b) {
            return b.length - a.length;
        }

        var minPieces = [],
            shortPieces = [],
            longPieces = [],
            mixedPieces = [],
            i,
            mom,
            minp,
            shortp,
            longp;
        for (i = 0; i < 7; i++) {
            // make the regex if we don't have it already
            mom = createUTC([2000, 1]).day(i);
            minp = this.weekdaysMin(mom, '');
            shortp = this.weekdaysShort(mom, '');
            longp = this.weekdays(mom, '');
            minPieces.push(minp);
            shortPieces.push(shortp);
            longPieces.push(longp);
            mixedPieces.push(minp);
            mixedPieces.push(shortp);
            mixedPieces.push(longp);
        }
        // Sorting makes sure if one weekday (or abbr) is a prefix of another it
        // will match the longer piece.
        minPieces.sort(cmpLenRev);
        shortPieces.sort(cmpLenRev);
        longPieces.sort(cmpLenRev);
        mixedPieces.sort(cmpLenRev);
        for (i = 0; i < 7; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }

        this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
        this._weekdaysShortRegex = this._weekdaysRegex;
        this._weekdaysMinRegex = this._weekdaysRegex;

        this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
        this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
        this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
    }

    // FORMATTING

    function hFormat() {
        return this.hours() % 12 || 12;
    }

    function kFormat() {
        return this.hours() || 24;
    }

    addFormatToken('H', ['HH', 2], 0, 'hour');
    addFormatToken('h', ['hh', 2], 0, hFormat);
    addFormatToken('k', ['kk', 2], 0, kFormat);

    addFormatToken('hmm', 0, 0, function () {
        return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
    });

    addFormatToken('hmmss', 0, 0, function () {
        return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
    });

    addFormatToken('Hmm', 0, 0, function () {
        return '' + this.hours() + zeroFill(this.minutes(), 2);
    });

    addFormatToken('Hmmss', 0, 0, function () {
        return '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
    });

    function meridiem(token, lowercase) {
        addFormatToken(token, 0, 0, function () {
            return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
        });
    }

    meridiem('a', true);
    meridiem('A', false);

    // ALIASES

    addUnitAlias('hour', 'h');

    // PRIORITY
    addUnitPriority('hour', 13);

    // PARSING

    function matchMeridiem(isStrict, locale) {
        return locale._meridiemParse;
    }

    addRegexToken('a', matchMeridiem);
    addRegexToken('A', matchMeridiem);
    addRegexToken('H', match1to2);
    addRegexToken('h', match1to2);
    addRegexToken('HH', match1to2, match2);
    addRegexToken('hh', match1to2, match2);

    addRegexToken('hmm', match3to4);
    addRegexToken('hmmss', match5to6);
    addRegexToken('Hmm', match3to4);
    addRegexToken('Hmmss', match5to6);

    addParseToken(['H', 'HH'], HOUR);
    addParseToken(['a', 'A'], function (input, array, config) {
        config._isPm = config._locale.isPM(input);
        config._meridiem = input;
    });
    addParseToken(['h', 'hh'], function (input, array, config) {
        array[HOUR] = toInt(input);
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('hmm', function (input, array, config) {
        var pos = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos));
        array[MINUTE] = toInt(input.substr(pos));
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('hmmss', function (input, array, config) {
        var pos1 = input.length - 4;
        var pos2 = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos1));
        array[MINUTE] = toInt(input.substr(pos1, 2));
        array[SECOND] = toInt(input.substr(pos2));
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('Hmm', function (input, array, config) {
        var pos = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos));
        array[MINUTE] = toInt(input.substr(pos));
    });
    addParseToken('Hmmss', function (input, array, config) {
        var pos1 = input.length - 4;
        var pos2 = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos1));
        array[MINUTE] = toInt(input.substr(pos1, 2));
        array[SECOND] = toInt(input.substr(pos2));
    });

    // LOCALES

    function localeIsPM(input) {
        // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
        // Using charAt should be more compatible.
        return (input + '').toLowerCase().charAt(0) === 'p';
    }

    var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
    function localeMeridiem(hours, minutes, isLower) {
        if (hours > 11) {
            return isLower ? 'pm' : 'PM';
        } else {
            return isLower ? 'am' : 'AM';
        }
    }

    // MOMENTS

    // Setting the hour should keep the time, because the user explicitly
    // specified which hour he wants. So trying to maintain the same hour (in
    // a new timezone) makes sense. Adding/subtracting hours does not follow
    // this rule.
    var getSetHour = makeGetSet('Hours', true);

    // months
    // week
    // weekdays
    // meridiem
    var baseConfig = {
        calendar: defaultCalendar,
        longDateFormat: defaultLongDateFormat,
        invalidDate: defaultInvalidDate,
        ordinal: defaultOrdinal,
        ordinalParse: defaultOrdinalParse,
        relativeTime: defaultRelativeTime,

        months: defaultLocaleMonths,
        monthsShort: defaultLocaleMonthsShort,

        week: defaultLocaleWeek,

        weekdays: defaultLocaleWeekdays,
        weekdaysMin: defaultLocaleWeekdaysMin,
        weekdaysShort: defaultLocaleWeekdaysShort,

        meridiemParse: defaultLocaleMeridiemParse
    };

    // internal storage for locale config files
    var locales = {};
    var localeFamilies = {};
    var globalLocale;

    function normalizeLocale(key) {
        return key ? key.toLowerCase().replace('_', '-') : key;
    }

    // pick the locale from the array
    // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
    // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
    function chooseLocale(names) {
        var i = 0,
            j,
            next,
            locale,
            split;

        while (i < names.length) {
            split = normalizeLocale(names[i]).split('-');
            j = split.length;
            next = normalizeLocale(names[i + 1]);
            next = next ? next.split('-') : null;
            while (j > 0) {
                locale = loadLocale(split.slice(0, j).join('-'));
                if (locale) {
                    return locale;
                }
                if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
                    //the next array item is better than a shallower substring of this one
                    break;
                }
                j--;
            }
            i++;
        }
        return null;
    }

    function loadLocale(name) {
        var oldLocale = null;
        // TODO: Find a better way to register and load all the locales in Node
        if (!locales[name] && typeof module !== 'undefined' && module && module.exports) {
            try {
                oldLocale = globalLocale._abbr;
                require('./locale/' + name);
                // because defineLocale currently also sets the global locale, we
                // want to undo that for lazy loaded locales
                getSetGlobalLocale(oldLocale);
            } catch (e) {}
        }
        return locales[name];
    }

    // This function will load locale and then set the global locale.  If
    // no arguments are passed in, it will simply return the current global
    // locale key.
    function getSetGlobalLocale(key, values) {
        var data;
        if (key) {
            if (isUndefined(values)) {
                data = getLocale(key);
            } else {
                data = defineLocale(key, values);
            }

            if (data) {
                // moment.duration._locale = moment._locale = data;
                globalLocale = data;
            }
        }

        return globalLocale._abbr;
    }

    function defineLocale(name, config) {
        if (config !== null) {
            var parentConfig = baseConfig;
            config.abbr = name;
            if (locales[name] != null) {
                deprecateSimple('defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
                parentConfig = locales[name]._config;
            } else if (config.parentLocale != null) {
                if (locales[config.parentLocale] != null) {
                    parentConfig = locales[config.parentLocale]._config;
                } else {
                    if (!localeFamilies[config.parentLocale]) {
                        localeFamilies[config.parentLocale] = [];
                    }
                    localeFamilies[config.parentLocale].push({
                        name: name,
                        config: config
                    });
                    return null;
                }
            }
            locales[name] = new Locale(mergeConfigs(parentConfig, config));

            if (localeFamilies[name]) {
                localeFamilies[name].forEach(function (x) {
                    defineLocale(x.name, x.config);
                });
            }

            // backwards compat for now: also set the locale
            // make sure we set the locale AFTER all child locales have been
            // created, so we won't end up with the child locale set.
            getSetGlobalLocale(name);

            return locales[name];
        } else {
            // useful for testing
            delete locales[name];
            return null;
        }
    }

    function updateLocale(name, config) {
        if (config != null) {
            var locale,
                parentConfig = baseConfig;
            // MERGE
            if (locales[name] != null) {
                parentConfig = locales[name]._config;
            }
            config = mergeConfigs(parentConfig, config);
            locale = new Locale(config);
            locale.parentLocale = locales[name];
            locales[name] = locale;

            // backwards compat for now: also set the locale
            getSetGlobalLocale(name);
        } else {
            // pass null for config to unupdate, useful for tests
            if (locales[name] != null) {
                if (locales[name].parentLocale != null) {
                    locales[name] = locales[name].parentLocale;
                } else if (locales[name] != null) {
                    delete locales[name];
                }
            }
        }
        return locales[name];
    }

    // returns locale data
    function getLocale(key) {
        var locale;

        if (key && key._locale && key._locale._abbr) {
            key = key._locale._abbr;
        }

        if (!key) {
            return globalLocale;
        }

        if (!isArray(key)) {
            //short-circuit everything else
            locale = loadLocale(key);
            if (locale) {
                return locale;
            }
            key = [key];
        }

        return chooseLocale(key);
    }

    function listLocales() {
        return keys$1(locales);
    }

    function checkOverflow(m) {
        var overflow;
        var a = m._a;

        if (a && getParsingFlags(m).overflow === -2) {
            overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1;

            if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
                overflow = DATE;
            }
            if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
                overflow = WEEK;
            }
            if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
                overflow = WEEKDAY;
            }

            getParsingFlags(m).overflow = overflow;
        }

        return m;
    }

    // iso 8601 regex
    // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
    var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
    var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;

    var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;

    var isoDates = [['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/],
    // YYYYMM is NOT allowed by the standard
    ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/]];

    // iso time formats and regexes
    var isoTimes = [['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/]];

    var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;

    // date from iso format
    function configFromISO(config) {
        var i,
            l,
            string = config._i,
            match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
            allowTime,
            dateFormat,
            timeFormat,
            tzFormat;

        if (match) {
            getParsingFlags(config).iso = true;

            for (i = 0, l = isoDates.length; i < l; i++) {
                if (isoDates[i][1].exec(match[1])) {
                    dateFormat = isoDates[i][0];
                    allowTime = isoDates[i][2] !== false;
                    break;
                }
            }
            if (dateFormat == null) {
                config._isValid = false;
                return;
            }
            if (match[3]) {
                for (i = 0, l = isoTimes.length; i < l; i++) {
                    if (isoTimes[i][1].exec(match[3])) {
                        // match[2] should be 'T' or space
                        timeFormat = (match[2] || ' ') + isoTimes[i][0];
                        break;
                    }
                }
                if (timeFormat == null) {
                    config._isValid = false;
                    return;
                }
            }
            if (!allowTime && timeFormat != null) {
                config._isValid = false;
                return;
            }
            if (match[4]) {
                if (tzRegex.exec(match[4])) {
                    tzFormat = 'Z';
                } else {
                    config._isValid = false;
                    return;
                }
            }
            config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
            configFromStringAndFormat(config);
        } else {
            config._isValid = false;
        }
    }

    // date from iso format or fallback
    function configFromString(config) {
        var matched = aspNetJsonRegex.exec(config._i);

        if (matched !== null) {
            config._d = new Date(+matched[1]);
            return;
        }

        configFromISO(config);
        if (config._isValid === false) {
            delete config._isValid;
            hooks.createFromInputFallback(config);
        }
    }

    hooks.createFromInputFallback = deprecate('value provided is not in a recognized ISO format. moment construction falls back to js Date(), ' + 'which is not reliable across all browsers and versions. Non ISO date formats are ' + 'discouraged and will be removed in an upcoming major release. Please refer to ' + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) {
        config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
    });

    // Pick the first defined of two or three arguments.
    function defaults(a, b, c) {
        if (a != null) {
            return a;
        }
        if (b != null) {
            return b;
        }
        return c;
    }

    function currentDateArray(config) {
        // hooks is actually the exported moment object
        var nowValue = new Date(hooks.now());
        if (config._useUTC) {
            return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
        }
        return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
    }

    // convert an array to a date.
    // the array should mirror the parameters below
    // note: all values past the year are optional and will default to the lowest possible value.
    // [year, month, day , hour, minute, second, millisecond]
    function configFromArray(config) {
        var i,
            date,
            input = [],
            currentDate,
            yearToUse;

        if (config._d) {
            return;
        }

        currentDate = currentDateArray(config);

        //compute day of the year from weeks and weekdays
        if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
            dayOfYearFromWeekInfo(config);
        }

        //if the day of the year is set, figure out what it is
        if (config._dayOfYear) {
            yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);

            if (config._dayOfYear > daysInYear(yearToUse)) {
                getParsingFlags(config)._overflowDayOfYear = true;
            }

            date = createUTCDate(yearToUse, 0, config._dayOfYear);
            config._a[MONTH] = date.getUTCMonth();
            config._a[DATE] = date.getUTCDate();
        }

        // Default to current date.
        // * if no year, month, day of month are given, default to today
        // * if day of month is given, default month and year
        // * if month is given, default only year
        // * if year is given, don't default anything
        for (i = 0; i < 3 && config._a[i] == null; ++i) {
            config._a[i] = input[i] = currentDate[i];
        }

        // Zero out whatever was not defaulted, including time
        for (; i < 7; i++) {
            config._a[i] = input[i] = config._a[i] == null ? i === 2 ? 1 : 0 : config._a[i];
        }

        // Check for 24:00:00.000
        if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) {
            config._nextDay = true;
            config._a[HOUR] = 0;
        }

        config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
        // Apply timezone offset from input. The actual utcOffset can be changed
        // with parseZone.
        if (config._tzm != null) {
            config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
        }

        if (config._nextDay) {
            config._a[HOUR] = 24;
        }
    }

    function dayOfYearFromWeekInfo(config) {
        var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;

        w = config._w;
        if (w.GG != null || w.W != null || w.E != null) {
            dow = 1;
            doy = 4;

            // TODO: We need to take the current isoWeekYear, but that depends on
            // how we interpret now (local, utc, fixed offset). So create
            // a now version of current config (take local/utc/offset flags, and
            // create now).
            weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
            week = defaults(w.W, 1);
            weekday = defaults(w.E, 1);
            if (weekday < 1 || weekday > 7) {
                weekdayOverflow = true;
            }
        } else {
            dow = config._locale._week.dow;
            doy = config._locale._week.doy;

            var curWeek = weekOfYear(createLocal(), dow, doy);

            weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);

            // Default to current week.
            week = defaults(w.w, curWeek.week);

            if (w.d != null) {
                // weekday -- low day numbers are considered next week
                weekday = w.d;
                if (weekday < 0 || weekday > 6) {
                    weekdayOverflow = true;
                }
            } else if (w.e != null) {
                // local weekday -- counting starts from begining of week
                weekday = w.e + dow;
                if (w.e < 0 || w.e > 6) {
                    weekdayOverflow = true;
                }
            } else {
                // default to begining of week
                weekday = dow;
            }
        }
        if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
            getParsingFlags(config)._overflowWeeks = true;
        } else if (weekdayOverflow != null) {
            getParsingFlags(config)._overflowWeekday = true;
        } else {
            temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
            config._a[YEAR] = temp.year;
            config._dayOfYear = temp.dayOfYear;
        }
    }

    // constant that refers to the ISO standard
    hooks.ISO_8601 = function () {};

    // date from string and format string
    function configFromStringAndFormat(config) {
        // TODO: Move this to another part of the creation flow to prevent circular deps
        if (config._f === hooks.ISO_8601) {
            configFromISO(config);
            return;
        }

        config._a = [];
        getParsingFlags(config).empty = true;

        // This array is used to make a Date, either with `new Date` or `Date.UTC`
        var string = '' + config._i,
            i,
            parsedInput,
            tokens,
            token,
            skipped,
            stringLength = string.length,
            totalParsedInputLength = 0;

        tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];

        for (i = 0; i < tokens.length; i++) {
            token = tokens[i];
            parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
            // console.log('token', token, 'parsedInput', parsedInput,
            //         'regex', getParseRegexForToken(token, config));
            if (parsedInput) {
                skipped = string.substr(0, string.indexOf(parsedInput));
                if (skipped.length > 0) {
                    getParsingFlags(config).unusedInput.push(skipped);
                }
                string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
                totalParsedInputLength += parsedInput.length;
            }
            // don't parse if it's not a known token
            if (formatTokenFunctions[token]) {
                if (parsedInput) {
                    getParsingFlags(config).empty = false;
                } else {
                    getParsingFlags(config).unusedTokens.push(token);
                }
                addTimeToArrayFromToken(token, parsedInput, config);
            } else if (config._strict && !parsedInput) {
                getParsingFlags(config).unusedTokens.push(token);
            }
        }

        // add remaining unparsed input length to the string
        getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
        if (string.length > 0) {
            getParsingFlags(config).unusedInput.push(string);
        }

        // clear _12h flag if hour is <= 12
        if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) {
            getParsingFlags(config).bigHour = undefined;
        }

        getParsingFlags(config).parsedDateParts = config._a.slice(0);
        getParsingFlags(config).meridiem = config._meridiem;
        // handle meridiem
        config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);

        configFromArray(config);
        checkOverflow(config);
    }

    function meridiemFixWrap(locale, hour, meridiem) {
        var isPm;

        if (meridiem == null) {
            // nothing to do
            return hour;
        }
        if (locale.meridiemHour != null) {
            return locale.meridiemHour(hour, meridiem);
        } else if (locale.isPM != null) {
            // Fallback
            isPm = locale.isPM(meridiem);
            if (isPm && hour < 12) {
                hour += 12;
            }
            if (!isPm && hour === 12) {
                hour = 0;
            }
            return hour;
        } else {
            // this is not supposed to happen
            return hour;
        }
    }

    // date from string and array of format strings
    function configFromStringAndArray(config) {
        var tempConfig, bestMoment, scoreToBeat, i, currentScore;

        if (config._f.length === 0) {
            getParsingFlags(config).invalidFormat = true;
            config._d = new Date(NaN);
            return;
        }

        for (i = 0; i < config._f.length; i++) {
            currentScore = 0;
            tempConfig = copyConfig({}, config);
            if (config._useUTC != null) {
                tempConfig._useUTC = config._useUTC;
            }
            tempConfig._f = config._f[i];
            configFromStringAndFormat(tempConfig);

            if (!isValid(tempConfig)) {
                continue;
            }

            // if there is any input that was not parsed add a penalty for that format
            currentScore += getParsingFlags(tempConfig).charsLeftOver;

            //or tokens
            currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;

            getParsingFlags(tempConfig).score = currentScore;

            if (scoreToBeat == null || currentScore < scoreToBeat) {
                scoreToBeat = currentScore;
                bestMoment = tempConfig;
            }
        }

        extend(config, bestMoment || tempConfig);
    }

    function configFromObject(config) {
        if (config._d) {
            return;
        }

        var i = normalizeObjectUnits(config._i);
        config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
            return obj && parseInt(obj, 10);
        });

        configFromArray(config);
    }

    function createFromConfig(config) {
        var res = new Moment(checkOverflow(prepareConfig(config)));
        if (res._nextDay) {
            // Adding is smart enough around DST
            res.add(1, 'd');
            res._nextDay = undefined;
        }

        return res;
    }

    function prepareConfig(config) {
        var input = config._i,
            format = config._f;

        config._locale = config._locale || getLocale(config._l);

        if (input === null || format === undefined && input === '') {
            return createInvalid({ nullInput: true });
        }

        if (typeof input === 'string') {
            config._i = input = config._locale.preparse(input);
        }

        if (isMoment(input)) {
            return new Moment(checkOverflow(input));
        } else if (isDate(input)) {
            config._d = input;
        } else if (isArray(format)) {
            configFromStringAndArray(config);
        } else if (format) {
            configFromStringAndFormat(config);
        } else {
            configFromInput(config);
        }

        if (!isValid(config)) {
            config._d = null;
        }

        return config;
    }

    function configFromInput(config) {
        var input = config._i;
        if (input === undefined) {
            config._d = new Date(hooks.now());
        } else if (isDate(input)) {
            config._d = new Date(input.valueOf());
        } else if (typeof input === 'string') {
            configFromString(config);
        } else if (isArray(input)) {
            config._a = map(input.slice(0), function (obj) {
                return parseInt(obj, 10);
            });
            configFromArray(config);
        } else if ((typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object') {
            configFromObject(config);
        } else if (isNumber(input)) {
            // from milliseconds
            config._d = new Date(input);
        } else {
            hooks.createFromInputFallback(config);
        }
    }

    function createLocalOrUTC(input, format, locale, strict, isUTC) {
        var c = {};

        if (locale === true || locale === false) {
            strict = locale;
            locale = undefined;
        }

        if (isObject(input) && isObjectEmpty(input) || isArray(input) && input.length === 0) {
            input = undefined;
        }
        // object construction must be done this way.
        // https://github.com/moment/moment/issues/1423
        c._isAMomentObject = true;
        c._useUTC = c._isUTC = isUTC;
        c._l = locale;
        c._i = input;
        c._f = format;
        c._strict = strict;

        return createFromConfig(c);
    }

    function createLocal(input, format, locale, strict) {
        return createLocalOrUTC(input, format, locale, strict, false);
    }

    var prototypeMin = deprecate('moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
        var other = createLocal.apply(null, arguments);
        if (this.isValid() && other.isValid()) {
            return other < this ? this : other;
        } else {
            return createInvalid();
        }
    });

    var prototypeMax = deprecate('moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
        var other = createLocal.apply(null, arguments);
        if (this.isValid() && other.isValid()) {
            return other > this ? this : other;
        } else {
            return createInvalid();
        }
    });

    // Pick a moment m from moments so that m[fn](other) is true for all
    // other. This relies on the function fn to be transitive.
    //
    // moments should either be an array of moment objects or an array, whose
    // first element is an array of moment objects.
    function pickBy(fn, moments) {
        var res, i;
        if (moments.length === 1 && isArray(moments[0])) {
            moments = moments[0];
        }
        if (!moments.length) {
            return createLocal();
        }
        res = moments[0];
        for (i = 1; i < moments.length; ++i) {
            if (!moments[i].isValid() || moments[i][fn](res)) {
                res = moments[i];
            }
        }
        return res;
    }

    // TODO: Use [].sort instead?
    function min() {
        var args = [].slice.call(arguments, 0);

        return pickBy('isBefore', args);
    }

    function max() {
        var args = [].slice.call(arguments, 0);

        return pickBy('isAfter', args);
    }

    var now = function now() {
        return Date.now ? Date.now() : +new Date();
    };

    function Duration(duration) {
        var normalizedInput = normalizeObjectUnits(duration),
            years = normalizedInput.year || 0,
            quarters = normalizedInput.quarter || 0,
            months = normalizedInput.month || 0,
            weeks = normalizedInput.week || 0,
            days = normalizedInput.day || 0,
            hours = normalizedInput.hour || 0,
            minutes = normalizedInput.minute || 0,
            seconds = normalizedInput.second || 0,
            milliseconds = normalizedInput.millisecond || 0;

        // representation for dateAddRemove
        this._milliseconds = +milliseconds + seconds * 1e3 + // 1000
        minutes * 6e4 + // 1000 * 60
        hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
        // Because of dateAddRemove treats 24 hours as different from a
        // day when working around DST, we need to store them separately
        this._days = +days + weeks * 7;
        // It is impossible translate months into days without knowing
        // which months you are are talking about, so we have to store
        // it separately.
        this._months = +months + quarters * 3 + years * 12;

        this._data = {};

        this._locale = getLocale();

        this._bubble();
    }

    function isDuration(obj) {
        return obj instanceof Duration;
    }

    function absRound(number) {
        if (number < 0) {
            return Math.round(-1 * number) * -1;
        } else {
            return Math.round(number);
        }
    }

    // FORMATTING

    function offset(token, separator) {
        addFormatToken(token, 0, 0, function () {
            var offset = this.utcOffset();
            var sign = '+';
            if (offset < 0) {
                offset = -offset;
                sign = '-';
            }
            return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~offset % 60, 2);
        });
    }

    offset('Z', ':');
    offset('ZZ', '');

    // PARSING

    addRegexToken('Z', matchShortOffset);
    addRegexToken('ZZ', matchShortOffset);
    addParseToken(['Z', 'ZZ'], function (input, array, config) {
        config._useUTC = true;
        config._tzm = offsetFromString(matchShortOffset, input);
    });

    // HELPERS

    // timezone chunker
    // '+10:00' > ['10',  '00']
    // '-1530'  > ['-15', '30']
    var chunkOffset = /([\+\-]|\d\d)/gi;

    function offsetFromString(matcher, string) {
        var matches = (string || '').match(matcher);

        if (matches === null) {
            return null;
        }

        var chunk = matches[matches.length - 1] || [];
        var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
        var minutes = +(parts[1] * 60) + toInt(parts[2]);

        return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
    }

    // Return a moment from input, that is local/utc/zone equivalent to model.
    function cloneWithOffset(input, model) {
        var res, diff;
        if (model._isUTC) {
            res = model.clone();
            diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
            // Use low-level api, because this fn is low-level api.
            res._d.setTime(res._d.valueOf() + diff);
            hooks.updateOffset(res, false);
            return res;
        } else {
            return createLocal(input).local();
        }
    }

    function getDateOffset(m) {
        // On Firefox.24 Date#getTimezoneOffset returns a floating point.
        // https://github.com/moment/moment/pull/1871
        return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
    }

    // HOOKS

    // This function will be called whenever a moment is mutated.
    // It is intended to keep the offset in sync with the timezone.
    hooks.updateOffset = function () {};

    // MOMENTS

    // keepLocalTime = true means only change the timezone, without
    // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
    // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
    // +0200, so we adjust the time as needed, to be valid.
    //
    // Keeping the time actually adds/subtracts (one hour)
    // from the actual represented time. That is why we call updateOffset
    // a second time. In case it wants us to change the offset again
    // _changeInProgress == true case, then we have to adjust, because
    // there is no such time in the given timezone.
    function getSetOffset(input, keepLocalTime) {
        var offset = this._offset || 0,
            localAdjust;
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        if (input != null) {
            if (typeof input === 'string') {
                input = offsetFromString(matchShortOffset, input);
                if (input === null) {
                    return this;
                }
            } else if (Math.abs(input) < 16) {
                input = input * 60;
            }
            if (!this._isUTC && keepLocalTime) {
                localAdjust = getDateOffset(this);
            }
            this._offset = input;
            this._isUTC = true;
            if (localAdjust != null) {
                this.add(localAdjust, 'm');
            }
            if (offset !== input) {
                if (!keepLocalTime || this._changeInProgress) {
                    addSubtract(this, createDuration(input - offset, 'm'), 1, false);
                } else if (!this._changeInProgress) {
                    this._changeInProgress = true;
                    hooks.updateOffset(this, true);
                    this._changeInProgress = null;
                }
            }
            return this;
        } else {
            return this._isUTC ? offset : getDateOffset(this);
        }
    }

    function getSetZone(input, keepLocalTime) {
        if (input != null) {
            if (typeof input !== 'string') {
                input = -input;
            }

            this.utcOffset(input, keepLocalTime);

            return this;
        } else {
            return -this.utcOffset();
        }
    }

    function setOffsetToUTC(keepLocalTime) {
        return this.utcOffset(0, keepLocalTime);
    }

    function setOffsetToLocal(keepLocalTime) {
        if (this._isUTC) {
            this.utcOffset(0, keepLocalTime);
            this._isUTC = false;

            if (keepLocalTime) {
                this.subtract(getDateOffset(this), 'm');
            }
        }
        return this;
    }

    function setOffsetToParsedOffset() {
        if (this._tzm != null) {
            this.utcOffset(this._tzm);
        } else if (typeof this._i === 'string') {
            var tZone = offsetFromString(matchOffset, this._i);
            if (tZone != null) {
                this.utcOffset(tZone);
            } else {
                this.utcOffset(0, true);
            }
        }
        return this;
    }

    function hasAlignedHourOffset(input) {
        if (!this.isValid()) {
            return false;
        }
        input = input ? createLocal(input).utcOffset() : 0;

        return (this.utcOffset() - input) % 60 === 0;
    }

    function isDaylightSavingTime() {
        return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset();
    }

    function isDaylightSavingTimeShifted() {
        if (!isUndefined(this._isDSTShifted)) {
            return this._isDSTShifted;
        }

        var c = {};

        copyConfig(c, this);
        c = prepareConfig(c);

        if (c._a) {
            var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
            this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0;
        } else {
            this._isDSTShifted = false;
        }

        return this._isDSTShifted;
    }

    function isLocal() {
        return this.isValid() ? !this._isUTC : false;
    }

    function isUtcOffset() {
        return this.isValid() ? this._isUTC : false;
    }

    function isUtc() {
        return this.isValid() ? this._isUTC && this._offset === 0 : false;
    }

    // ASP.NET json date format regex
    var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;

    // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
    // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
    // and further modified to allow for strings containing both week and day
    var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;

    function createDuration(input, key) {
        var duration = input,

        // matching against regexp is expensive, do it on demand
        match = null,
            sign,
            ret,
            diffRes;

        if (isDuration(input)) {
            duration = {
                ms: input._milliseconds,
                d: input._days,
                M: input._months
            };
        } else if (isNumber(input)) {
            duration = {};
            if (key) {
                duration[key] = input;
            } else {
                duration.milliseconds = input;
            }
        } else if (!!(match = aspNetRegex.exec(input))) {
            sign = match[1] === '-' ? -1 : 1;
            duration = {
                y: 0,
                d: toInt(match[DATE]) * sign,
                h: toInt(match[HOUR]) * sign,
                m: toInt(match[MINUTE]) * sign,
                s: toInt(match[SECOND]) * sign,
                ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
            };
        } else if (!!(match = isoRegex.exec(input))) {
            sign = match[1] === '-' ? -1 : 1;
            duration = {
                y: parseIso(match[2], sign),
                M: parseIso(match[3], sign),
                w: parseIso(match[4], sign),
                d: parseIso(match[5], sign),
                h: parseIso(match[6], sign),
                m: parseIso(match[7], sign),
                s: parseIso(match[8], sign)
            };
        } else if (duration == null) {
            // checks for null or undefined
            duration = {};
        } else if ((typeof duration === 'undefined' ? 'undefined' : _typeof(duration)) === 'object' && ('from' in duration || 'to' in duration)) {
            diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));

            duration = {};
            duration.ms = diffRes.milliseconds;
            duration.M = diffRes.months;
        }

        ret = new Duration(duration);

        if (isDuration(input) && hasOwnProp(input, '_locale')) {
            ret._locale = input._locale;
        }

        return ret;
    }

    createDuration.fn = Duration.prototype;

    function parseIso(inp, sign) {
        // We'd normally use ~~inp for this, but unfortunately it also
        // converts floats to ints.
        // inp may be undefined, so careful calling replace on it.
        var res = inp && parseFloat(inp.replace(',', '.'));
        // apply sign while we're at it
        return (isNaN(res) ? 0 : res) * sign;
    }

    function positiveMomentsDifference(base, other) {
        var res = { milliseconds: 0, months: 0 };

        res.months = other.month() - base.month() + (other.year() - base.year()) * 12;
        if (base.clone().add(res.months, 'M').isAfter(other)) {
            --res.months;
        }

        res.milliseconds = +other - +base.clone().add(res.months, 'M');

        return res;
    }

    function momentsDifference(base, other) {
        var res;
        if (!(base.isValid() && other.isValid())) {
            return { milliseconds: 0, months: 0 };
        }

        other = cloneWithOffset(other, base);
        if (base.isBefore(other)) {
            res = positiveMomentsDifference(base, other);
        } else {
            res = positiveMomentsDifference(other, base);
            res.milliseconds = -res.milliseconds;
            res.months = -res.months;
        }

        return res;
    }

    // TODO: remove 'name' arg after deprecation is removed
    function createAdder(direction, name) {
        return function (val, period) {
            var dur, tmp;
            //invert the arguments, but complain about it
            if (period !== null && !isNaN(+period)) {
                deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
                tmp = val;val = period;period = tmp;
            }

            val = typeof val === 'string' ? +val : val;
            dur = createDuration(val, period);
            addSubtract(this, dur, direction);
            return this;
        };
    }

    function addSubtract(mom, duration, isAdding, updateOffset) {
        var milliseconds = duration._milliseconds,
            days = absRound(duration._days),
            months = absRound(duration._months);

        if (!mom.isValid()) {
            // No op
            return;
        }

        updateOffset = updateOffset == null ? true : updateOffset;

        if (milliseconds) {
            mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
        }
        if (days) {
            set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
        }
        if (months) {
            setMonth(mom, get(mom, 'Month') + months * isAdding);
        }
        if (updateOffset) {
            hooks.updateOffset(mom, days || months);
        }
    }

    var add = createAdder(1, 'add');
    var subtract = createAdder(-1, 'subtract');

    function getCalendarFormat(myMoment, now) {
        var diff = myMoment.diff(now, 'days', true);
        return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse';
    }

    function calendar$1(time, formats) {
        // We want to compare the start of today, vs this.
        // Getting start-of-today depends on whether we're local/utc/offset or not.
        var now = time || createLocal(),
            sod = cloneWithOffset(now, this).startOf('day'),
            format = hooks.calendarFormat(this, sod) || 'sameElse';

        var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);

        return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
    }

    function clone() {
        return new Moment(this);
    }

    function isAfter(input, units) {
        var localInput = isMoment(input) ? input : createLocal(input);
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() > localInput.valueOf();
        } else {
            return localInput.valueOf() < this.clone().startOf(units).valueOf();
        }
    }

    function isBefore(input, units) {
        var localInput = isMoment(input) ? input : createLocal(input);
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() < localInput.valueOf();
        } else {
            return this.clone().endOf(units).valueOf() < localInput.valueOf();
        }
    }

    function isBetween(from, to, units, inclusivity) {
        inclusivity = inclusivity || '()';
        return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) && (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
    }

    function isSame(input, units) {
        var localInput = isMoment(input) ? input : createLocal(input),
            inputMs;
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(units || 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() === localInput.valueOf();
        } else {
            inputMs = localInput.valueOf();
            return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
        }
    }

    function isSameOrAfter(input, units) {
        return this.isSame(input, units) || this.isAfter(input, units);
    }

    function isSameOrBefore(input, units) {
        return this.isSame(input, units) || this.isBefore(input, units);
    }

    function diff(input, units, asFloat) {
        var that, zoneDelta, delta, output;

        if (!this.isValid()) {
            return NaN;
        }

        that = cloneWithOffset(input, this);

        if (!that.isValid()) {
            return NaN;
        }

        zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;

        units = normalizeUnits(units);

        if (units === 'year' || units === 'month' || units === 'quarter') {
            output = monthDiff(this, that);
            if (units === 'quarter') {
                output = output / 3;
            } else if (units === 'year') {
                output = output / 12;
            }
        } else {
            delta = this - that;
            output = units === 'second' ? delta / 1e3 : // 1000
            units === 'minute' ? delta / 6e4 : // 1000 * 60
            units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
            units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
            units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
            delta;
        }
        return asFloat ? output : absFloor(output);
    }

    function monthDiff(a, b) {
        // difference in months
        var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),

        // b is in (anchor - 1 month, anchor + 1 month)
        anchor = a.clone().add(wholeMonthDiff, 'months'),
            anchor2,
            adjust;

        if (b - anchor < 0) {
            anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor - anchor2);
        } else {
            anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor2 - anchor);
        }

        //check for negative zero, return zero if negative zero
        return -(wholeMonthDiff + adjust) || 0;
    }

    hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
    hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';

    function toString() {
        return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
    }

    function toISOString() {
        var m = this.clone().utc();
        if (0 < m.year() && m.year() <= 9999) {
            if (isFunction(Date.prototype.toISOString)) {
                // native implementation is ~50x faster, use it when we can
                return this.toDate().toISOString();
            } else {
                return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
            }
        } else {
            return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
        }
    }

    /**
     * Return a human readable representation of a moment that can
     * also be evaluated to get a new moment which is the same
     *
     * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
     */
    function inspect() {
        if (!this.isValid()) {
            return 'moment.invalid(/* ' + this._i + ' */)';
        }
        var func = 'moment';
        var zone = '';
        if (!this.isLocal()) {
            func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
            zone = 'Z';
        }
        var prefix = '[' + func + '("]';
        var year = 0 < this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
        var datetime = '-MM-DD[T]HH:mm:ss.SSS';
        var suffix = zone + '[")]';

        return this.format(prefix + year + datetime + suffix);
    }

    function format(inputString) {
        if (!inputString) {
            inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
        }
        var output = formatMoment(this, inputString);
        return this.localeData().postformat(output);
    }

    function from(time, withoutSuffix) {
        if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
            return createDuration({ to: this, from: time }).locale(this.locale()).humanize(!withoutSuffix);
        } else {
            return this.localeData().invalidDate();
        }
    }

    function fromNow(withoutSuffix) {
        return this.from(createLocal(), withoutSuffix);
    }

    function to(time, withoutSuffix) {
        if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
            return createDuration({ from: this, to: time }).locale(this.locale()).humanize(!withoutSuffix);
        } else {
            return this.localeData().invalidDate();
        }
    }

    function toNow(withoutSuffix) {
        return this.to(createLocal(), withoutSuffix);
    }

    // If passed a locale key, it will set the locale for this
    // instance.  Otherwise, it will return the locale configuration
    // variables for this instance.
    function locale(key) {
        var newLocaleData;

        if (key === undefined) {
            return this._locale._abbr;
        } else {
            newLocaleData = getLocale(key);
            if (newLocaleData != null) {
                this._locale = newLocaleData;
            }
            return this;
        }
    }

    var lang = deprecate('moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) {
        if (key === undefined) {
            return this.localeData();
        } else {
            return this.locale(key);
        }
    });

    function localeData() {
        return this._locale;
    }

    function startOf(units) {
        units = normalizeUnits(units);
        // the following switch intentionally omits break keywords
        // to utilize falling through the cases.
        switch (units) {
            case 'year':
                this.month(0);
            /* falls through */
            case 'quarter':
            case 'month':
                this.date(1);
            /* falls through */
            case 'week':
            case 'isoWeek':
            case 'day':
            case 'date':
                this.hours(0);
            /* falls through */
            case 'hour':
                this.minutes(0);
            /* falls through */
            case 'minute':
                this.seconds(0);
            /* falls through */
            case 'second':
                this.milliseconds(0);
        }

        // weeks are a special case
        if (units === 'week') {
            this.weekday(0);
        }
        if (units === 'isoWeek') {
            this.isoWeekday(1);
        }

        // quarters are also special
        if (units === 'quarter') {
            this.month(Math.floor(this.month() / 3) * 3);
        }

        return this;
    }

    function endOf(units) {
        units = normalizeUnits(units);
        if (units === undefined || units === 'millisecond') {
            return this;
        }

        // 'date' is an alias for 'day', so it should be considered as such.
        if (units === 'date') {
            units = 'day';
        }

        return this.startOf(units).add(1, units === 'isoWeek' ? 'week' : units).subtract(1, 'ms');
    }

    function valueOf() {
        return this._d.valueOf() - (this._offset || 0) * 60000;
    }

    function unix() {
        return Math.floor(this.valueOf() / 1000);
    }

    function toDate() {
        return new Date(this.valueOf());
    }

    function toArray() {
        var m = this;
        return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
    }

    function toObject() {
        var m = this;
        return {
            years: m.year(),
            months: m.month(),
            date: m.date(),
            hours: m.hours(),
            minutes: m.minutes(),
            seconds: m.seconds(),
            milliseconds: m.milliseconds()
        };
    }

    function toJSON() {
        // new Date(NaN).toJSON() === null
        return this.isValid() ? this.toISOString() : null;
    }

    function isValid$1() {
        return isValid(this);
    }

    function parsingFlags() {
        return extend({}, getParsingFlags(this));
    }

    function invalidAt() {
        return getParsingFlags(this).overflow;
    }

    function creationData() {
        return {
            input: this._i,
            format: this._f,
            locale: this._locale,
            isUTC: this._isUTC,
            strict: this._strict
        };
    }

    // FORMATTING

    addFormatToken(0, ['gg', 2], 0, function () {
        return this.weekYear() % 100;
    });

    addFormatToken(0, ['GG', 2], 0, function () {
        return this.isoWeekYear() % 100;
    });

    function addWeekYearFormatToken(token, getter) {
        addFormatToken(0, [token, token.length], 0, getter);
    }

    addWeekYearFormatToken('gggg', 'weekYear');
    addWeekYearFormatToken('ggggg', 'weekYear');
    addWeekYearFormatToken('GGGG', 'isoWeekYear');
    addWeekYearFormatToken('GGGGG', 'isoWeekYear');

    // ALIASES

    addUnitAlias('weekYear', 'gg');
    addUnitAlias('isoWeekYear', 'GG');

    // PRIORITY

    addUnitPriority('weekYear', 1);
    addUnitPriority('isoWeekYear', 1);

    // PARSING

    addRegexToken('G', matchSigned);
    addRegexToken('g', matchSigned);
    addRegexToken('GG', match1to2, match2);
    addRegexToken('gg', match1to2, match2);
    addRegexToken('GGGG', match1to4, match4);
    addRegexToken('gggg', match1to4, match4);
    addRegexToken('GGGGG', match1to6, match6);
    addRegexToken('ggggg', match1to6, match6);

    addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
        week[token.substr(0, 2)] = toInt(input);
    });

    addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
        week[token] = hooks.parseTwoDigitYear(input);
    });

    // MOMENTS

    function getSetWeekYear(input) {
        return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy);
    }

    function getSetISOWeekYear(input) {
        return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4);
    }

    function getISOWeeksInYear() {
        return weeksInYear(this.year(), 1, 4);
    }

    function getWeeksInYear() {
        var weekInfo = this.localeData()._week;
        return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
    }

    function getSetWeekYearHelper(input, week, weekday, dow, doy) {
        var weeksTarget;
        if (input == null) {
            return weekOfYear(this, dow, doy).year;
        } else {
            weeksTarget = weeksInYear(input, dow, doy);
            if (week > weeksTarget) {
                week = weeksTarget;
            }
            return setWeekAll.call(this, input, week, weekday, dow, doy);
        }
    }

    function setWeekAll(weekYear, week, weekday, dow, doy) {
        var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
            date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);

        this.year(date.getUTCFullYear());
        this.month(date.getUTCMonth());
        this.date(date.getUTCDate());
        return this;
    }

    // FORMATTING

    addFormatToken('Q', 0, 'Qo', 'quarter');

    // ALIASES

    addUnitAlias('quarter', 'Q');

    // PRIORITY

    addUnitPriority('quarter', 7);

    // PARSING

    addRegexToken('Q', match1);
    addParseToken('Q', function (input, array) {
        array[MONTH] = (toInt(input) - 1) * 3;
    });

    // MOMENTS

    function getSetQuarter(input) {
        return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
    }

    // FORMATTING

    addFormatToken('D', ['DD', 2], 'Do', 'date');

    // ALIASES

    addUnitAlias('date', 'D');

    // PRIOROITY
    addUnitPriority('date', 9);

    // PARSING

    addRegexToken('D', match1to2);
    addRegexToken('DD', match1to2, match2);
    addRegexToken('Do', function (isStrict, locale) {
        return isStrict ? locale._ordinalParse : locale._ordinalParseLenient;
    });

    addParseToken(['D', 'DD'], DATE);
    addParseToken('Do', function (input, array) {
        array[DATE] = toInt(input.match(match1to2)[0], 10);
    });

    // MOMENTS

    var getSetDayOfMonth = makeGetSet('Date', true);

    // FORMATTING

    addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');

    // ALIASES

    addUnitAlias('dayOfYear', 'DDD');

    // PRIORITY
    addUnitPriority('dayOfYear', 4);

    // PARSING

    addRegexToken('DDD', match1to3);
    addRegexToken('DDDD', match3);
    addParseToken(['DDD', 'DDDD'], function (input, array, config) {
        config._dayOfYear = toInt(input);
    });

    // HELPERS

    // MOMENTS

    function getSetDayOfYear(input) {
        var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
        return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
    }

    // FORMATTING

    addFormatToken('m', ['mm', 2], 0, 'minute');

    // ALIASES

    addUnitAlias('minute', 'm');

    // PRIORITY

    addUnitPriority('minute', 14);

    // PARSING

    addRegexToken('m', match1to2);
    addRegexToken('mm', match1to2, match2);
    addParseToken(['m', 'mm'], MINUTE);

    // MOMENTS

    var getSetMinute = makeGetSet('Minutes', false);

    // FORMATTING

    addFormatToken('s', ['ss', 2], 0, 'second');

    // ALIASES

    addUnitAlias('second', 's');

    // PRIORITY

    addUnitPriority('second', 15);

    // PARSING

    addRegexToken('s', match1to2);
    addRegexToken('ss', match1to2, match2);
    addParseToken(['s', 'ss'], SECOND);

    // MOMENTS

    var getSetSecond = makeGetSet('Seconds', false);

    // FORMATTING

    addFormatToken('S', 0, 0, function () {
        return ~~(this.millisecond() / 100);
    });

    addFormatToken(0, ['SS', 2], 0, function () {
        return ~~(this.millisecond() / 10);
    });

    addFormatToken(0, ['SSS', 3], 0, 'millisecond');
    addFormatToken(0, ['SSSS', 4], 0, function () {
        return this.millisecond() * 10;
    });
    addFormatToken(0, ['SSSSS', 5], 0, function () {
        return this.millisecond() * 100;
    });
    addFormatToken(0, ['SSSSSS', 6], 0, function () {
        return this.millisecond() * 1000;
    });
    addFormatToken(0, ['SSSSSSS', 7], 0, function () {
        return this.millisecond() * 10000;
    });
    addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
        return this.millisecond() * 100000;
    });
    addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
        return this.millisecond() * 1000000;
    });

    // ALIASES

    addUnitAlias('millisecond', 'ms');

    // PRIORITY

    addUnitPriority('millisecond', 16);

    // PARSING

    addRegexToken('S', match1to3, match1);
    addRegexToken('SS', match1to3, match2);
    addRegexToken('SSS', match1to3, match3);

    var token;
    for (token = 'SSSS'; token.length <= 9; token += 'S') {
        addRegexToken(token, matchUnsigned);
    }

    function parseMs(input, array) {
        array[MILLISECOND] = toInt(('0.' + input) * 1000);
    }

    for (token = 'S'; token.length <= 9; token += 'S') {
        addParseToken(token, parseMs);
    }
    // MOMENTS

    var getSetMillisecond = makeGetSet('Milliseconds', false);

    // FORMATTING

    addFormatToken('z', 0, 0, 'zoneAbbr');
    addFormatToken('zz', 0, 0, 'zoneName');

    // MOMENTS

    function getZoneAbbr() {
        return this._isUTC ? 'UTC' : '';
    }

    function getZoneName() {
        return this._isUTC ? 'Coordinated Universal Time' : '';
    }

    var proto = Moment.prototype;

    proto.add = add;
    proto.calendar = calendar$1;
    proto.clone = clone;
    proto.diff = diff;
    proto.endOf = endOf;
    proto.format = format;
    proto.from = from;
    proto.fromNow = fromNow;
    proto.to = to;
    proto.toNow = toNow;
    proto.get = stringGet;
    proto.invalidAt = invalidAt;
    proto.isAfter = isAfter;
    proto.isBefore = isBefore;
    proto.isBetween = isBetween;
    proto.isSame = isSame;
    proto.isSameOrAfter = isSameOrAfter;
    proto.isSameOrBefore = isSameOrBefore;
    proto.isValid = isValid$1;
    proto.lang = lang;
    proto.locale = locale;
    proto.localeData = localeData;
    proto.max = prototypeMax;
    proto.min = prototypeMin;
    proto.parsingFlags = parsingFlags;
    proto.set = stringSet;
    proto.startOf = startOf;
    proto.subtract = subtract;
    proto.toArray = toArray;
    proto.toObject = toObject;
    proto.toDate = toDate;
    proto.toISOString = toISOString;
    proto.inspect = inspect;
    proto.toJSON = toJSON;
    proto.toString = toString;
    proto.unix = unix;
    proto.valueOf = valueOf;
    proto.creationData = creationData;

    // Year
    proto.year = getSetYear;
    proto.isLeapYear = getIsLeapYear;

    // Week Year
    proto.weekYear = getSetWeekYear;
    proto.isoWeekYear = getSetISOWeekYear;

    // Quarter
    proto.quarter = proto.quarters = getSetQuarter;

    // Month
    proto.month = getSetMonth;
    proto.daysInMonth = getDaysInMonth;

    // Week
    proto.week = proto.weeks = getSetWeek;
    proto.isoWeek = proto.isoWeeks = getSetISOWeek;
    proto.weeksInYear = getWeeksInYear;
    proto.isoWeeksInYear = getISOWeeksInYear;

    // Day
    proto.date = getSetDayOfMonth;
    proto.day = proto.days = getSetDayOfWeek;
    proto.weekday = getSetLocaleDayOfWeek;
    proto.isoWeekday = getSetISODayOfWeek;
    proto.dayOfYear = getSetDayOfYear;

    // Hour
    proto.hour = proto.hours = getSetHour;

    // Minute
    proto.minute = proto.minutes = getSetMinute;

    // Second
    proto.second = proto.seconds = getSetSecond;

    // Millisecond
    proto.millisecond = proto.milliseconds = getSetMillisecond;

    // Offset
    proto.utcOffset = getSetOffset;
    proto.utc = setOffsetToUTC;
    proto.local = setOffsetToLocal;
    proto.parseZone = setOffsetToParsedOffset;
    proto.hasAlignedHourOffset = hasAlignedHourOffset;
    proto.isDST = isDaylightSavingTime;
    proto.isLocal = isLocal;
    proto.isUtcOffset = isUtcOffset;
    proto.isUtc = isUtc;
    proto.isUTC = isUtc;

    // Timezone
    proto.zoneAbbr = getZoneAbbr;
    proto.zoneName = getZoneName;

    // Deprecations
    proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
    proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
    proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
    proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
    proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);

    function createUnix(input) {
        return createLocal(input * 1000);
    }

    function createInZone() {
        return createLocal.apply(null, arguments).parseZone();
    }

    function preParsePostFormat(string) {
        return string;
    }

    var proto$1 = Locale.prototype;

    proto$1.calendar = calendar;
    proto$1.longDateFormat = longDateFormat;
    proto$1.invalidDate = invalidDate;
    proto$1.ordinal = ordinal;
    proto$1.preparse = preParsePostFormat;
    proto$1.postformat = preParsePostFormat;
    proto$1.relativeTime = relativeTime;
    proto$1.pastFuture = pastFuture;
    proto$1.set = set;

    // Month
    proto$1.months = localeMonths;
    proto$1.monthsShort = localeMonthsShort;
    proto$1.monthsParse = localeMonthsParse;
    proto$1.monthsRegex = monthsRegex;
    proto$1.monthsShortRegex = monthsShortRegex;

    // Week
    proto$1.week = localeWeek;
    proto$1.firstDayOfYear = localeFirstDayOfYear;
    proto$1.firstDayOfWeek = localeFirstDayOfWeek;

    // Day of Week
    proto$1.weekdays = localeWeekdays;
    proto$1.weekdaysMin = localeWeekdaysMin;
    proto$1.weekdaysShort = localeWeekdaysShort;
    proto$1.weekdaysParse = localeWeekdaysParse;

    proto$1.weekdaysRegex = weekdaysRegex;
    proto$1.weekdaysShortRegex = weekdaysShortRegex;
    proto$1.weekdaysMinRegex = weekdaysMinRegex;

    // Hours
    proto$1.isPM = localeIsPM;
    proto$1.meridiem = localeMeridiem;

    function get$1(format, index, field, setter) {
        var locale = getLocale();
        var utc = createUTC().set(setter, index);
        return locale[field](utc, format);
    }

    function listMonthsImpl(format, index, field) {
        if (isNumber(format)) {
            index = format;
            format = undefined;
        }

        format = format || '';

        if (index != null) {
            return get$1(format, index, field, 'month');
        }

        var i;
        var out = [];
        for (i = 0; i < 12; i++) {
            out[i] = get$1(format, i, field, 'month');
        }
        return out;
    }

    // ()
    // (5)
    // (fmt, 5)
    // (fmt)
    // (true)
    // (true, 5)
    // (true, fmt, 5)
    // (true, fmt)
    function listWeekdaysImpl(localeSorted, format, index, field) {
        if (typeof localeSorted === 'boolean') {
            if (isNumber(format)) {
                index = format;
                format = undefined;
            }

            format = format || '';
        } else {
            format = localeSorted;
            index = format;
            localeSorted = false;

            if (isNumber(format)) {
                index = format;
                format = undefined;
            }

            format = format || '';
        }

        var locale = getLocale(),
            shift = localeSorted ? locale._week.dow : 0;

        if (index != null) {
            return get$1(format, (index + shift) % 7, field, 'day');
        }

        var i;
        var out = [];
        for (i = 0; i < 7; i++) {
            out[i] = get$1(format, (i + shift) % 7, field, 'day');
        }
        return out;
    }

    function listMonths(format, index) {
        return listMonthsImpl(format, index, 'months');
    }

    function listMonthsShort(format, index) {
        return listMonthsImpl(format, index, 'monthsShort');
    }

    function listWeekdays(localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
    }

    function listWeekdaysShort(localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
    }

    function listWeekdaysMin(localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
    }

    getSetGlobalLocale('en', {
        ordinalParse: /\d{1,2}(th|st|nd|rd)/,
        ordinal: function ordinal(number) {
            var b = number % 10,
                output = toInt(number % 100 / 10) === 1 ? 'th' : b === 1 ? 'st' : b === 2 ? 'nd' : b === 3 ? 'rd' : 'th';
            return number + output;
        }
    });

    // Side effect imports
    hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
    hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);

    var mathAbs = Math.abs;

    function abs() {
        var data = this._data;

        this._milliseconds = mathAbs(this._milliseconds);
        this._days = mathAbs(this._days);
        this._months = mathAbs(this._months);

        data.milliseconds = mathAbs(data.milliseconds);
        data.seconds = mathAbs(data.seconds);
        data.minutes = mathAbs(data.minutes);
        data.hours = mathAbs(data.hours);
        data.months = mathAbs(data.months);
        data.years = mathAbs(data.years);

        return this;
    }

    function addSubtract$1(duration, input, value, direction) {
        var other = createDuration(input, value);

        duration._milliseconds += direction * other._milliseconds;
        duration._days += direction * other._days;
        duration._months += direction * other._months;

        return duration._bubble();
    }

    // supports only 2.0-style add(1, 's') or add(duration)
    function add$1(input, value) {
        return addSubtract$1(this, input, value, 1);
    }

    // supports only 2.0-style subtract(1, 's') or subtract(duration)
    function subtract$1(input, value) {
        return addSubtract$1(this, input, value, -1);
    }

    function absCeil(number) {
        if (number < 0) {
            return Math.floor(number);
        } else {
            return Math.ceil(number);
        }
    }

    function bubble() {
        var milliseconds = this._milliseconds;
        var days = this._days;
        var months = this._months;
        var data = this._data;
        var seconds, minutes, hours, years, monthsFromDays;

        // if we have a mix of positive and negative values, bubble down first
        // check: https://github.com/moment/moment/issues/2166
        if (!(milliseconds >= 0 && days >= 0 && months >= 0 || milliseconds <= 0 && days <= 0 && months <= 0)) {
            milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
            days = 0;
            months = 0;
        }

        // The following code bubbles up values, see the tests for
        // examples of what that means.
        data.milliseconds = milliseconds % 1000;

        seconds = absFloor(milliseconds / 1000);
        data.seconds = seconds % 60;

        minutes = absFloor(seconds / 60);
        data.minutes = minutes % 60;

        hours = absFloor(minutes / 60);
        data.hours = hours % 24;

        days += absFloor(hours / 24);

        // convert days to months
        monthsFromDays = absFloor(daysToMonths(days));
        months += monthsFromDays;
        days -= absCeil(monthsToDays(monthsFromDays));

        // 12 months -> 1 year
        years = absFloor(months / 12);
        months %= 12;

        data.days = days;
        data.months = months;
        data.years = years;

        return this;
    }

    function daysToMonths(days) {
        // 400 years have 146097 days (taking into account leap year rules)
        // 400 years have 12 months === 4800
        return days * 4800 / 146097;
    }

    function monthsToDays(months) {
        // the reverse of daysToMonths
        return months * 146097 / 4800;
    }

    function as(units) {
        var days;
        var months;
        var milliseconds = this._milliseconds;

        units = normalizeUnits(units);

        if (units === 'month' || units === 'year') {
            days = this._days + milliseconds / 864e5;
            months = this._months + daysToMonths(days);
            return units === 'month' ? months : months / 12;
        } else {
            // handle milliseconds separately because of floating point math errors (issue #1867)
            days = this._days + Math.round(monthsToDays(this._months));
            switch (units) {
                case 'week':
                    return days / 7 + milliseconds / 6048e5;
                case 'day':
                    return days + milliseconds / 864e5;
                case 'hour':
                    return days * 24 + milliseconds / 36e5;
                case 'minute':
                    return days * 1440 + milliseconds / 6e4;
                case 'second':
                    return days * 86400 + milliseconds / 1000;
                // Math.floor prevents floating point math errors here
                case 'millisecond':
                    return Math.floor(days * 864e5) + milliseconds;
                default:
                    throw new Error('Unknown unit ' + units);
            }
        }
    }

    // TODO: Use this.as('ms')?
    function valueOf$1() {
        return this._milliseconds + this._days * 864e5 + this._months % 12 * 2592e6 + toInt(this._months / 12) * 31536e6;
    }

    function makeAs(alias) {
        return function () {
            return this.as(alias);
        };
    }

    var asMilliseconds = makeAs('ms');
    var asSeconds = makeAs('s');
    var asMinutes = makeAs('m');
    var asHours = makeAs('h');
    var asDays = makeAs('d');
    var asWeeks = makeAs('w');
    var asMonths = makeAs('M');
    var asYears = makeAs('y');

    function get$2(units) {
        units = normalizeUnits(units);
        return this[units + 's']();
    }

    function makeGetter(name) {
        return function () {
            return this._data[name];
        };
    }

    var milliseconds = makeGetter('milliseconds');
    var seconds = makeGetter('seconds');
    var minutes = makeGetter('minutes');
    var hours = makeGetter('hours');
    var days = makeGetter('days');
    var months = makeGetter('months');
    var years = makeGetter('years');

    function weeks() {
        return absFloor(this.days() / 7);
    }

    var round = Math.round;
    var thresholds = {
        s: 45, // seconds to minute
        m: 45, // minutes to hour
        h: 22, // hours to day
        d: 26, // days to month
        M: 11 // months to year
    };

    // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
    function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
        return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
    }

    function relativeTime$1(posNegDuration, withoutSuffix, locale) {
        var duration = createDuration(posNegDuration).abs();
        var seconds = round(duration.as('s'));
        var minutes = round(duration.as('m'));
        var hours = round(duration.as('h'));
        var days = round(duration.as('d'));
        var months = round(duration.as('M'));
        var years = round(duration.as('y'));

        var a = seconds < thresholds.s && ['s', seconds] || minutes <= 1 && ['m'] || minutes < thresholds.m && ['mm', minutes] || hours <= 1 && ['h'] || hours < thresholds.h && ['hh', hours] || days <= 1 && ['d'] || days < thresholds.d && ['dd', days] || months <= 1 && ['M'] || months < thresholds.M && ['MM', months] || years <= 1 && ['y'] || ['yy', years];

        a[2] = withoutSuffix;
        a[3] = +posNegDuration > 0;
        a[4] = locale;
        return substituteTimeAgo.apply(null, a);
    }

    // This function allows you to set the rounding function for relative time strings
    function getSetRelativeTimeRounding(roundingFunction) {
        if (roundingFunction === undefined) {
            return round;
        }
        if (typeof roundingFunction === 'function') {
            round = roundingFunction;
            return true;
        }
        return false;
    }

    // This function allows you to set a threshold for relative time strings
    function getSetRelativeTimeThreshold(threshold, limit) {
        if (thresholds[threshold] === undefined) {
            return false;
        }
        if (limit === undefined) {
            return thresholds[threshold];
        }
        thresholds[threshold] = limit;
        return true;
    }

    function humanize(withSuffix) {
        var locale = this.localeData();
        var output = relativeTime$1(this, !withSuffix, locale);

        if (withSuffix) {
            output = locale.pastFuture(+this, output);
        }

        return locale.postformat(output);
    }

    var abs$1 = Math.abs;

    function toISOString$1() {
        // for ISO strings we do not use the normal bubbling rules:
        //  * milliseconds bubble up until they become hours
        //  * days do not bubble at all
        //  * months bubble up until they become years
        // This is because there is no context-free conversion between hours and days
        // (think of clock changes)
        // and also not between days and months (28-31 days per month)
        var seconds = abs$1(this._milliseconds) / 1000;
        var days = abs$1(this._days);
        var months = abs$1(this._months);
        var minutes, hours, years;

        // 3600 seconds -> 60 minutes -> 1 hour
        minutes = absFloor(seconds / 60);
        hours = absFloor(minutes / 60);
        seconds %= 60;
        minutes %= 60;

        // 12 months -> 1 year
        years = absFloor(months / 12);
        months %= 12;

        // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
        var Y = years;
        var M = months;
        var D = days;
        var h = hours;
        var m = minutes;
        var s = seconds;
        var total = this.asSeconds();

        if (!total) {
            // this is the same as C#'s (Noda) and python (isodate)...
            // but not other JS (goog.date)
            return 'P0D';
        }

        return (total < 0 ? '-' : '') + 'P' + (Y ? Y + 'Y' : '') + (M ? M + 'M' : '') + (D ? D + 'D' : '') + (h || m || s ? 'T' : '') + (h ? h + 'H' : '') + (m ? m + 'M' : '') + (s ? s + 'S' : '');
    }

    var proto$2 = Duration.prototype;

    proto$2.abs = abs;
    proto$2.add = add$1;
    proto$2.subtract = subtract$1;
    proto$2.as = as;
    proto$2.asMilliseconds = asMilliseconds;
    proto$2.asSeconds = asSeconds;
    proto$2.asMinutes = asMinutes;
    proto$2.asHours = asHours;
    proto$2.asDays = asDays;
    proto$2.asWeeks = asWeeks;
    proto$2.asMonths = asMonths;
    proto$2.asYears = asYears;
    proto$2.valueOf = valueOf$1;
    proto$2._bubble = bubble;
    proto$2.get = get$2;
    proto$2.milliseconds = milliseconds;
    proto$2.seconds = seconds;
    proto$2.minutes = minutes;
    proto$2.hours = hours;
    proto$2.days = days;
    proto$2.weeks = weeks;
    proto$2.months = months;
    proto$2.years = years;
    proto$2.humanize = humanize;
    proto$2.toISOString = toISOString$1;
    proto$2.toString = toISOString$1;
    proto$2.toJSON = toISOString$1;
    proto$2.locale = locale;
    proto$2.localeData = localeData;

    // Deprecations
    proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
    proto$2.lang = lang;

    // Side effect imports

    // FORMATTING

    addFormatToken('X', 0, 0, 'unix');
    addFormatToken('x', 0, 0, 'valueOf');

    // PARSING

    addRegexToken('x', matchSigned);
    addRegexToken('X', matchTimestamp);
    addParseToken('X', function (input, array, config) {
        config._d = new Date(parseFloat(input, 10) * 1000);
    });
    addParseToken('x', function (input, array, config) {
        config._d = new Date(toInt(input));
    });

    // Side effect imports


    hooks.version = '2.17.1';

    setHookCallback(createLocal);

    hooks.fn = proto;
    hooks.min = min;
    hooks.max = max;
    hooks.now = now;
    hooks.utc = createUTC;
    hooks.unix = createUnix;
    hooks.months = listMonths;
    hooks.isDate = isDate;
    hooks.locale = getSetGlobalLocale;
    hooks.invalid = createInvalid;
    hooks.duration = createDuration;
    hooks.isMoment = isMoment;
    hooks.weekdays = listWeekdays;
    hooks.parseZone = createInZone;
    hooks.localeData = getLocale;
    hooks.isDuration = isDuration;
    hooks.monthsShort = listMonthsShort;
    hooks.weekdaysMin = listWeekdaysMin;
    hooks.defineLocale = defineLocale;
    hooks.updateLocale = updateLocale;
    hooks.locales = listLocales;
    hooks.weekdaysShort = listWeekdaysShort;
    hooks.normalizeUnits = normalizeUnits;
    hooks.relativeTimeRounding = getSetRelativeTimeRounding;
    hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
    hooks.calendarFormat = getCalendarFormat;
    hooks.prototype = proto;

    return hooks;
}); 
 			}); 		define("utils/q.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

// vim:ts=4:sts=4:sw=4:
/*!
 *
 * Copyright 2009-2017 Kris Kowal under the terms of the MIT
 * license found at https://github.com/kriskowal/q/blob/v1/LICENSE
 *
 * With parts by Tyler Close
 * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found
 * at http://www.opensource.org/licenses/mit-license.html
 * Forked at ref_send.js version: 2009-05-11
 *
 * With parts by Mark Miller
 * Copyright (C) 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

(function (definition) {
    "use strict";

    module.exports = definition();
})(function () {
    "use strict";

    var hasStacks = false;
    try {
        throw new Error();
    } catch (e) {
        hasStacks = !!e.stack;
    }

    // All code after this point will be filtered from stack traces reported
    // by Q.
    var qStartingLine = captureLine();
    var qFileName;

    // shims

    // used for fallback in "allResolved"
    var noop = function noop() {};

    // Use the fastest possible means to execute a task in a future turn
    // of the event loop.
    var nextTick = function () {
        // linked list of tasks (single, with head node)
        var head = { task: void 0, next: null };
        var tail = head;
        var flushing = false;
        var requestTick = void 0;
        var isNodeJS = false;
        // queue for late tasks, used by unhandled rejection tracking
        var laterQueue = [];

        function flush() {
            /* jshint loopfunc: true */
            var task, domain;

            while (head.next) {
                head = head.next;
                task = head.task;
                head.task = void 0;
                domain = head.domain;

                if (domain) {
                    head.domain = void 0;
                    domain.enter();
                }
                runSingle(task, domain);
            }
            while (laterQueue.length) {
                task = laterQueue.pop();
                runSingle(task);
            }
            flushing = false;
        }
        // runs a single function in the async queue
        function runSingle(task, domain) {
            try {
                task();
            } catch (e) {
                if (isNodeJS) {
                    // In node, uncaught exceptions are considered fatal errors.
                    // Re-throw them synchronously to interrupt flushing!

                    // Ensure continuation if the uncaught exception is suppressed
                    // listening "uncaughtException" events (as domains does).
                    // Continue in next event to avoid tick recursion.
                    if (domain) {
                        domain.exit();
                    }
                    setTimeout(flush, 0);
                    if (domain) {
                        domain.enter();
                    }

                    throw e;
                } else {
                    // In browsers, uncaught exceptions are not fatal.
                    // Re-throw them asynchronously to avoid slow-downs.
                    setTimeout(function () {
                        throw e;
                    }, 0);
                }
            }

            if (domain) {
                domain.exit();
            }
        }

        nextTick = function nextTick(task) {
            tail = tail.next = {
                task: task,
                domain: isNodeJS && process.domain,
                next: null
            };

            if (!flushing) {
                flushing = true;
                requestTick();
            }
        };

        if ((typeof process === "undefined" ? "undefined" : _typeof(process)) === "object" && process.toString() === "[object process]" && process.nextTick) {
            // Ensure Q is in a real Node environment, with a `process.nextTick`.
            // To see through fake Node environments:
            // * Mocha test runner - exposes a `process` global without a `nextTick`
            // * Browserify - exposes a `process.nexTick` function that uses
            //   `setTimeout`. In this case `setImmediate` is preferred because
            //    it is faster. Browserify's `process.toString()` yields
            //   "[object Object]", while in a real Node environment
            //   `process.nextTick()` yields "[object process]".
            isNodeJS = true;

            requestTick = function requestTick() {
                process.nextTick(flush);
            };
        } else if (typeof setImmediate === "function") {
            // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
            if (typeof window !== "undefined") {
                requestTick = setImmediate.bind(window, flush);
            } else {
                requestTick = function requestTick() {
                    setImmediate(flush);
                };
            }
        } else if (typeof MessageChannel !== "undefined") {
            // modern browsers
            // http://www.nonblocking.io/2011/06/windownexttick.html
            var channel = new MessageChannel();
            // At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create
            // working message ports the first time a page loads.
            channel.port1.onmessage = function () {
                requestTick = requestPortTick;
                channel.port1.onmessage = flush;
                flush();
            };
            var requestPortTick = function requestPortTick() {
                // Opera requires us to provide a message payload, regardless of
                // whether we use it.
                channel.port2.postMessage(0);
            };
            requestTick = function requestTick() {
                setTimeout(flush, 0);
                requestPortTick();
            };
        } else {
            // old browsers
            requestTick = function requestTick() {
                setTimeout(flush, 0);
            };
        }
        // runs a task after all other tasks have been run
        // this is useful for unhandled rejection tracking that needs to happen
        // after all `then`d tasks have been run.
        nextTick.runAfter = function (task) {
            laterQueue.push(task);
            if (!flushing) {
                flushing = true;
                requestTick();
            }
        };
        return nextTick;
    }();

    // Attempt to make generics safe in the face of downstream
    // modifications.
    // There is no situation where this is necessary.
    // If you need a security guarantee, these primordials need to be
    // deeply frozen anyway, and if you don’t need a security guarantee,
    // this is just plain paranoid.
    // However, this **might** have the nice side-effect of reducing the size of
    // the minified code by reducing x.call() to merely x()
    // See Mark Miller’s explanation of what this does.
    // http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming
    var call = Function.call;
    function uncurryThis(f) {
        return function () {
            return call.apply(f, arguments);
        };
    }
    // This is equivalent, but slower:
    // uncurryThis = Function_bind.bind(Function_bind.call);
    // http://jsperf.com/uncurrythis

    var array_slice = uncurryThis(Array.prototype.slice);

    var array_reduce = uncurryThis(Array.prototype.reduce || function (callback, basis) {
        var index = 0,
            length = this.length;
        // concerning the initial value, if one is not provided
        if (arguments.length === 1) {
            // seek to the first value in the array, accounting
            // for the possibility that is is a sparse array
            do {
                if (index in this) {
                    basis = this[index++];
                    break;
                }
                if (++index >= length) {
                    throw new TypeError();
                }
            } while (1);
        }
        // reduce
        for (; index < length; index++) {
            // account for the possibility that the array is sparse
            if (index in this) {
                basis = callback(basis, this[index], index);
            }
        }
        return basis;
    });

    var array_indexOf = uncurryThis(Array.prototype.indexOf || function (value) {
        // not a very good shim, but good enough for our one use of it
        for (var i = 0; i < this.length; i++) {
            if (this[i] === value) {
                return i;
            }
        }
        return -1;
    });

    var array_map = uncurryThis(Array.prototype.map || function (callback, thisp) {
        var self = this;
        var collect = [];
        array_reduce(self, function (undefined, value, index) {
            collect.push(callback.call(thisp, value, index, self));
        }, void 0);
        return collect;
    });

    var object_create = Object.create || function (prototype) {
        function Type() {}
        Type.prototype = prototype;
        return new Type();
    };

    var object_defineProperty = Object.defineProperty || function (obj, prop, descriptor) {
        obj[prop] = descriptor.value;
        return obj;
    };

    var object_hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty);

    var object_keys = Object.keys || function (object) {
        var keys = [];
        for (var key in object) {
            if (object_hasOwnProperty(object, key)) {
                keys.push(key);
            }
        }
        return keys;
    };

    var object_toString = uncurryThis(Object.prototype.toString);

    function isObject(value) {
        return value === Object(value);
    }

    // generator related shims

    // FIXME: Remove this function once ES6 generators are in SpiderMonkey.
    function isStopIteration(exception) {
        return object_toString(exception) === "[object StopIteration]" || exception instanceof QReturnValue;
    }

    // FIXME: Remove this helper and Q.return once ES6 generators are in
    // SpiderMonkey.
    var QReturnValue;
    if (typeof ReturnValue !== "undefined") {
        QReturnValue = ReturnValue;
    } else {
        QReturnValue = function QReturnValue(value) {
            this.value = value;
        };
    }

    // long stack traces

    var STACK_JUMP_SEPARATOR = "From previous event:";

    function makeStackTraceLong(error, promise) {
        // If possible, transform the error stack trace by removing Node and Q
        // cruft, then concatenating with the stack trace of `promise`. See #57.
        if (hasStacks && promise.stack && (typeof error === "undefined" ? "undefined" : _typeof(error)) === "object" && error !== null && error.stack) {
            var stacks = [];
            for (var p = promise; !!p; p = p.source) {
                if (p.stack && (!error.__minimumStackCounter__ || error.__minimumStackCounter__ > p.stackCounter)) {
                    object_defineProperty(error, "__minimumStackCounter__", { value: p.stackCounter, configurable: true });
                    stacks.unshift(p.stack);
                }
            }
            stacks.unshift(error.stack);

            var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
            var stack = filterStackString(concatedStacks);
            object_defineProperty(error, "stack", { value: stack, configurable: true });
        }
    }

    function filterStackString(stackString) {
        var lines = stackString.split("\n");
        var desiredLines = [];
        for (var i = 0; i < lines.length; ++i) {
            var line = lines[i];

            if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
                desiredLines.push(line);
            }
        }
        return desiredLines.join("\n");
    }

    function isNodeFrame(stackLine) {
        return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1;
    }

    function getFileNameAndLineNumber(stackLine) {
        // Named functions: "at functionName (filename:lineNumber:columnNumber)"
        // In IE10 function name can have spaces ("Anonymous function") O_o
        var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
        if (attempt1) {
            return [attempt1[1], Number(attempt1[2])];
        }

        // Anonymous functions: "at filename:lineNumber:columnNumber"
        var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
        if (attempt2) {
            return [attempt2[1], Number(attempt2[2])];
        }

        // Firefox style: "function@filename:lineNumber or @filename:lineNumber"
        var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
        if (attempt3) {
            return [attempt3[1], Number(attempt3[2])];
        }
    }

    function isInternalFrame(stackLine) {
        var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);

        if (!fileNameAndLineNumber) {
            return false;
        }

        var fileName = fileNameAndLineNumber[0];
        var lineNumber = fileNameAndLineNumber[1];

        return fileName === qFileName && lineNumber >= qStartingLine && lineNumber <= qEndingLine;
    }

    // discover own file name and line number range for filtering stack
    // traces
    function captureLine() {
        if (!hasStacks) {
            return;
        }

        try {
            throw new Error();
        } catch (e) {
            var lines = e.stack.split("\n");
            var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
            var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
            if (!fileNameAndLineNumber) {
                return;
            }

            qFileName = fileNameAndLineNumber[0];
            return fileNameAndLineNumber[1];
        }
    }

    function deprecate(callback, name, alternative) {
        return function () {
            if (typeof console !== "undefined" && typeof console.warn === "function") {
                console.warn(name + " is deprecated, use " + alternative + " instead.", new Error("").stack);
            }
            return callback.apply(callback, arguments);
        };
    }

    // end of shims
    // beginning of real work

    /**
     * Constructs a promise for an immediate reference, passes promises through, or
     * coerces promises from different systems.
     * @param value immediate reference or promise
     */
    function Q(value) {
        // If the object is already a Promise, return it directly.  This enables
        // the resolve function to both be used to created references from objects,
        // but to tolerably coerce non-promises to promises.
        if (value instanceof Promise) {
            return value;
        }

        // assimilate thenables
        if (isPromiseAlike(value)) {
            return coerce(value);
        } else {
            return fulfill(value);
        }
    }
    Q.resolve = Q;

    /**
     * Performs a task in a future turn of the event loop.
     * @param {Function} task
     */
    Q.nextTick = nextTick;

    /**
     * Controls whether or not long stack traces will be on
     */
    Q.longStackSupport = false;

    /**
     * The counter is used to determine the stopping point for building
     * long stack traces. In makeStackTraceLong we walk backwards through
     * the linked list of promises, only stacks which were created before
     * the rejection are concatenated.
     */
    var longStackCounter = 1;

    // enable long stacks if Q_DEBUG is set
    if ((typeof process === "undefined" ? "undefined" : _typeof(process)) === "object" && process && process.env && process.env.Q_DEBUG) {
        Q.longStackSupport = true;
    }

    /**
     * Constructs a {promise, resolve, reject} object.
     *
     * `resolve` is a callback to invoke with a more resolved value for the
     * promise. To fulfill the promise, invoke `resolve` with any value that is
     * not a thenable. To reject the promise, invoke `resolve` with a rejected
     * thenable, or invoke `reject` with the reason directly. To resolve the
     * promise to another thenable, thus putting it in the same state, invoke
     * `resolve` with that other thenable.
     */
    Q.defer = defer;
    function defer() {
        // if "messages" is an "Array", that indicates that the promise has not yet
        // been resolved.  If it is "undefined", it has been resolved.  Each
        // element of the messages array is itself an array of complete arguments to
        // forward to the resolved promise.  We coerce the resolution value to a
        // promise using the `resolve` function because it handles both fully
        // non-thenable values and other thenables gracefully.
        var messages = [],
            progressListeners = [],
            resolvedPromise;

        var deferred = object_create(defer.prototype);
        var promise = object_create(Promise.prototype);

        promise.promiseDispatch = function (resolve, op, operands) {
            var args = array_slice(arguments);
            if (messages) {
                messages.push(args);
                if (op === "when" && operands[1]) {
                    // progress operand
                    progressListeners.push(operands[1]);
                }
            } else {
                Q.nextTick(function () {
                    resolvedPromise.promiseDispatch.apply(resolvedPromise, args);
                });
            }
        };

        // XXX deprecated
        promise.valueOf = function () {
            if (messages) {
                return promise;
            }
            var nearerValue = nearer(resolvedPromise);
            if (isPromise(nearerValue)) {
                resolvedPromise = nearerValue; // shorten chain
            }
            return nearerValue;
        };

        promise.inspect = function () {
            if (!resolvedPromise) {
                return { state: "pending" };
            }
            return resolvedPromise.inspect();
        };

        if (Q.longStackSupport && hasStacks) {
            try {
                throw new Error();
            } catch (e) {
                // NOTE: don't try to use `Error.captureStackTrace` or transfer the
                // accessor around; that causes memory leaks as per GH-111. Just
                // reify the stack trace as a string ASAP.
                //
                // At the same time, cut off the first line; it's always just
                // "[object Promise]\n", as per the `toString`.
                promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
                promise.stackCounter = longStackCounter++;
            }
        }

        // NOTE: we do the checks for `resolvedPromise` in each method, instead of
        // consolidating them into `become`, since otherwise we'd create new
        // promises with the lines `become(whatever(value))`. See e.g. GH-252.

        function become(newPromise) {
            resolvedPromise = newPromise;

            if (Q.longStackSupport && hasStacks) {
                // Only hold a reference to the new promise if long stacks
                // are enabled to reduce memory usage
                promise.source = newPromise;
            }

            array_reduce(messages, function (undefined, message) {
                Q.nextTick(function () {
                    newPromise.promiseDispatch.apply(newPromise, message);
                });
            }, void 0);

            messages = void 0;
            progressListeners = void 0;
        }

        deferred.promise = promise;
        deferred.resolve = function (value) {
            if (resolvedPromise) {
                return;
            }

            become(Q(value));
        };

        deferred.fulfill = function (value) {
            if (resolvedPromise) {
                return;
            }

            become(fulfill(value));
        };
        deferred.reject = function (reason) {
            if (resolvedPromise) {
                return;
            }

            become(reject(reason));
        };
        deferred.notify = function (progress) {
            if (resolvedPromise) {
                return;
            }

            array_reduce(progressListeners, function (undefined, progressListener) {
                Q.nextTick(function () {
                    progressListener(progress);
                });
            }, void 0);
        };

        return deferred;
    }

    /**
     * Creates a Node-style callback that will resolve or reject the deferred
     * promise.
     * @returns a nodeback
     */
    defer.prototype.makeNodeResolver = function () {
        var self = this;
        return function (error, value) {
            if (error) {
                self.reject(error);
            } else if (arguments.length > 2) {
                self.resolve(array_slice(arguments, 1));
            } else {
                self.resolve(value);
            }
        };
    };

    /**
     * @param resolver {Function} a function that returns nothing and accepts
     * the resolve, reject, and notify functions for a deferred.
     * @returns a promise that may be resolved with the given resolve and reject
     * functions, or rejected by a thrown exception in resolver
     */
    Q.Promise = promise; // ES6
    Q.promise = promise;
    function promise(resolver) {
        if (typeof resolver !== "function") {
            throw new TypeError("resolver must be a function.");
        }
        var deferred = defer();
        try {
            resolver(deferred.resolve, deferred.reject, deferred.notify);
        } catch (reason) {
            deferred.reject(reason);
        }
        return deferred.promise;
    }

    promise.race = race; // ES6
    promise.all = all; // ES6
    promise.reject = reject; // ES6
    promise.resolve = Q; // ES6

    // XXX experimental.  This method is a way to denote that a local value is
    // serializable and should be immediately dispatched to a remote upon request,
    // instead of passing a reference.
    Q.passByCopy = function (object) {
        //freeze(object);
        //passByCopies.set(object, true);
        return object;
    };

    Promise.prototype.passByCopy = function () {
        //freeze(object);
        //passByCopies.set(object, true);
        return this;
    };

    /**
     * If two promises eventually fulfill to the same value, promises that value,
     * but otherwise rejects.
     * @param x {Any*}
     * @param y {Any*}
     * @returns {Any*} a promise for x and y if they are the same, but a rejection
     * otherwise.
     *
     */
    Q.join = function (x, y) {
        return Q(x).join(y);
    };

    Promise.prototype.join = function (that) {
        return Q([this, that]).spread(function (x, y) {
            if (x === y) {
                // TODO: "===" should be Object.is or equiv
                return x;
            } else {
                throw new Error("Q can't join: not the same: " + x + " " + y);
            }
        });
    };

    /**
     * Returns a promise for the first of an array of promises to become settled.
     * @param answers {Array[Any*]} promises to race
     * @returns {Any*} the first promise to be settled
     */
    Q.race = race;
    function race(answerPs) {
        return promise(function (resolve, reject) {
            // Switch to this once we can assume at least ES5
            // answerPs.forEach(function (answerP) {
            //     Q(answerP).then(resolve, reject);
            // });
            // Use this in the meantime
            for (var i = 0, len = answerPs.length; i < len; i++) {
                Q(answerPs[i]).then(resolve, reject);
            }
        });
    }

    Promise.prototype.race = function () {
        return this.then(Q.race);
    };

    /**
     * Constructs a Promise with a promise descriptor object and optional fallback
     * function.  The descriptor contains methods like when(rejected), get(name),
     * set(name, value), post(name, args), and delete(name), which all
     * return either a value, a promise for a value, or a rejection.  The fallback
     * accepts the operation name, a resolver, and any further arguments that would
     * have been forwarded to the appropriate method above had a method been
     * provided with the proper name.  The API makes no guarantees about the nature
     * of the returned object, apart from that it is usable whereever promises are
     * bought and sold.
     */
    Q.makePromise = Promise;
    function Promise(descriptor, fallback, inspect) {
        if (fallback === void 0) {
            fallback = function fallback(op) {
                return reject(new Error("Promise does not support operation: " + op));
            };
        }
        if (inspect === void 0) {
            inspect = function inspect() {
                return { state: "unknown" };
            };
        }

        var promise = object_create(Promise.prototype);

        promise.promiseDispatch = function (resolve, op, args) {
            var result;
            try {
                if (descriptor[op]) {
                    result = descriptor[op].apply(promise, args);
                } else {
                    result = fallback.call(promise, op, args);
                }
            } catch (exception) {
                result = reject(exception);
            }
            if (resolve) {
                resolve(result);
            }
        };

        promise.inspect = inspect;

        // XXX deprecated `valueOf` and `exception` support
        if (inspect) {
            var inspected = inspect();
            if (inspected.state === "rejected") {
                promise.exception = inspected.reason;
            }

            promise.valueOf = function () {
                var inspected = inspect();
                if (inspected.state === "pending" || inspected.state === "rejected") {
                    return promise;
                }
                return inspected.value;
            };
        }

        return promise;
    }

    Promise.prototype.toString = function () {
        return "[object Promise]";
    };

    Promise.prototype.then = function (fulfilled, rejected, progressed) {
        var self = this;
        var deferred = defer();
        var done = false; // ensure the untrusted promise makes at most a
        // single call to one of the callbacks

        function _fulfilled(value) {
            try {
                return typeof fulfilled === "function" ? fulfilled(value) : value;
            } catch (exception) {
                return reject(exception);
            }
        }

        function _rejected(exception) {
            if (typeof rejected === "function") {
                makeStackTraceLong(exception, self);
                try {
                    return rejected(exception);
                } catch (newException) {
                    return reject(newException);
                }
            }
            return reject(exception);
        }

        function _progressed(value) {
            return typeof progressed === "function" ? progressed(value) : value;
        }

        Q.nextTick(function () {
            self.promiseDispatch(function (value) {
                if (done) {
                    return;
                }
                done = true;

                deferred.resolve(_fulfilled(value));
            }, "when", [function (exception) {
                if (done) {
                    return;
                }
                done = true;

                deferred.resolve(_rejected(exception));
            }]);
        });

        // Progress propagator need to be attached in the current tick.
        self.promiseDispatch(void 0, "when", [void 0, function (value) {
            var newValue;
            var threw = false;
            try {
                newValue = _progressed(value);
            } catch (e) {
                threw = true;
                if (Q.onerror) {
                    Q.onerror(e);
                } else {
                    throw e;
                }
            }

            if (!threw) {
                deferred.notify(newValue);
            }
        }]);

        return deferred.promise;
    };

    Q.tap = function (promise, callback) {
        return Q(promise).tap(callback);
    };

    /**
     * Works almost like "finally", but not called for rejections.
     * Original resolution value is passed through callback unaffected.
     * Callback may return a promise that will be awaited for.
     * @param {Function} callback
     * @returns {Q.Promise}
     * @example
     * doSomething()
     *   .then(...)
     *   .tap(console.log)
     *   .then(...);
     */
    Promise.prototype.tap = function (callback) {
        callback = Q(callback);

        return this.then(function (value) {
            return callback.fcall(value).thenResolve(value);
        });
    };

    /**
     * Registers an observer on a promise.
     *
     * Guarantees:
     *
     * 1. that fulfilled and rejected will be called only once.
     * 2. that either the fulfilled callback or the rejected callback will be
     *    called, but not both.
     * 3. that fulfilled and rejected will not be called in this turn.
     *
     * @param value      promise or immediate reference to observe
     * @param fulfilled  function to be called with the fulfilled value
     * @param rejected   function to be called with the rejection exception
     * @param progressed function to be called on any progress notifications
     * @return promise for the return value from the invoked callback
     */
    Q.when = when;
    function when(value, fulfilled, rejected, progressed) {
        return Q(value).then(fulfilled, rejected, progressed);
    }

    Promise.prototype.thenResolve = function (value) {
        return this.then(function () {
            return value;
        });
    };

    Q.thenResolve = function (promise, value) {
        return Q(promise).thenResolve(value);
    };

    Promise.prototype.thenReject = function (reason) {
        return this.then(function () {
            throw reason;
        });
    };

    Q.thenReject = function (promise, reason) {
        return Q(promise).thenReject(reason);
    };

    /**
     * If an object is not a promise, it is as "near" as possible.
     * If a promise is rejected, it is as "near" as possible too.
     * If it’s a fulfilled promise, the fulfillment value is nearer.
     * If it’s a deferred promise and the deferred has been resolved, the
     * resolution is "nearer".
     * @param object
     * @returns most resolved (nearest) form of the object
     */

    // XXX should we re-do this?
    Q.nearer = nearer;
    function nearer(value) {
        if (isPromise(value)) {
            var inspected = value.inspect();
            if (inspected.state === "fulfilled") {
                return inspected.value;
            }
        }
        return value;
    }

    /**
     * @returns whether the given object is a promise.
     * Otherwise it is a fulfilled value.
     */
    Q.isPromise = isPromise;
    function isPromise(object) {
        return object instanceof Promise;
    }

    Q.isPromiseAlike = isPromiseAlike;
    function isPromiseAlike(object) {
        return isObject(object) && typeof object.then === "function";
    }

    /**
     * @returns whether the given object is a pending promise, meaning not
     * fulfilled or rejected.
     */
    Q.isPending = isPending;
    function isPending(object) {
        return isPromise(object) && object.inspect().state === "pending";
    }

    Promise.prototype.isPending = function () {
        return this.inspect().state === "pending";
    };

    /**
     * @returns whether the given object is a value or fulfilled
     * promise.
     */
    Q.isFulfilled = isFulfilled;
    function isFulfilled(object) {
        return !isPromise(object) || object.inspect().state === "fulfilled";
    }

    Promise.prototype.isFulfilled = function () {
        return this.inspect().state === "fulfilled";
    };

    /**
     * @returns whether the given object is a rejected promise.
     */
    Q.isRejected = isRejected;
    function isRejected(object) {
        return isPromise(object) && object.inspect().state === "rejected";
    }

    Promise.prototype.isRejected = function () {
        return this.inspect().state === "rejected";
    };

    //// BEGIN UNHANDLED REJECTION TRACKING

    // This promise library consumes exceptions thrown in handlers so they can be
    // handled by a subsequent promise.  The exceptions get added to this array when
    // they are created, and removed when they are handled.  Note that in ES6 or
    // shimmed environments, this would naturally be a `Set`.
    var unhandledReasons = [];
    var unhandledRejections = [];
    var reportedUnhandledRejections = [];
    var trackUnhandledRejections = true;

    function resetUnhandledRejections() {
        unhandledReasons.length = 0;
        unhandledRejections.length = 0;

        if (!trackUnhandledRejections) {
            trackUnhandledRejections = true;
        }
    }

    function trackRejection(promise, reason) {
        if (!trackUnhandledRejections) {
            return;
        }
        if ((typeof process === "undefined" ? "undefined" : _typeof(process)) === "object" && typeof process.emit === "function") {
            Q.nextTick.runAfter(function () {
                if (array_indexOf(unhandledRejections, promise) !== -1) {
                    process.emit("unhandledRejection", reason, promise);
                    reportedUnhandledRejections.push(promise);
                }
            });
        }

        unhandledRejections.push(promise);
        if (reason && typeof reason.stack !== "undefined") {
            unhandledReasons.push(reason.stack);
        } else {
            unhandledReasons.push("(no stack) " + reason);
        }
    }

    function untrackRejection(promise) {
        if (!trackUnhandledRejections) {
            return;
        }

        var at = array_indexOf(unhandledRejections, promise);
        if (at !== -1) {
            if ((typeof process === "undefined" ? "undefined" : _typeof(process)) === "object" && typeof process.emit === "function") {
                Q.nextTick.runAfter(function () {
                    var atReport = array_indexOf(reportedUnhandledRejections, promise);
                    if (atReport !== -1) {
                        process.emit("rejectionHandled", unhandledReasons[at], promise);
                        reportedUnhandledRejections.splice(atReport, 1);
                    }
                });
            }
            unhandledRejections.splice(at, 1);
            unhandledReasons.splice(at, 1);
        }
    }

    Q.resetUnhandledRejections = resetUnhandledRejections;

    Q.getUnhandledReasons = function () {
        // Make a copy so that consumers can't interfere with our internal state.
        return unhandledReasons.slice();
    };

    Q.stopUnhandledRejectionTracking = function () {
        resetUnhandledRejections();
        trackUnhandledRejections = false;
    };

    resetUnhandledRejections();

    //// END UNHANDLED REJECTION TRACKING

    /**
     * Constructs a rejected promise.
     * @param reason value describing the failure
     */
    Q.reject = reject;
    function reject(reason) {
        var rejection = Promise({
            "when": function when(rejected) {
                // note that the error has been handled
                if (rejected) {
                    untrackRejection(this);
                }
                return rejected ? rejected(reason) : this;
            }
        }, function fallback() {
            return this;
        }, function inspect() {
            return { state: "rejected", reason: reason };
        });

        // Note that the reason has not been handled.
        trackRejection(rejection, reason);

        return rejection;
    }

    /**
     * Constructs a fulfilled promise for an immediate reference.
     * @param value immediate reference
     */
    Q.fulfill = fulfill;
    function fulfill(value) {
        return Promise({
            "when": function when() {
                return value;
            },
            "get": function get(name) {
                return value[name];
            },
            "set": function set(name, rhs) {
                value[name] = rhs;
            },
            "delete": function _delete(name) {
                delete value[name];
            },
            "post": function post(name, args) {
                // Mark Miller proposes that post with no name should apply a
                // promised function.
                if (name === null || name === void 0) {
                    return value.apply(void 0, args);
                } else {
                    return value[name].apply(value, args);
                }
            },
            "apply": function apply(thisp, args) {
                return value.apply(thisp, args);
            },
            "keys": function keys() {
                return object_keys(value);
            }
        }, void 0, function inspect() {
            return { state: "fulfilled", value: value };
        });
    }

    /**
     * Converts thenables to Q promises.
     * @param promise thenable promise
     * @returns a Q promise
     */
    function coerce(promise) {
        var deferred = defer();
        Q.nextTick(function () {
            try {
                promise.then(deferred.resolve, deferred.reject, deferred.notify);
            } catch (exception) {
                deferred.reject(exception);
            }
        });
        return deferred.promise;
    }

    /**
     * Annotates an object such that it will never be
     * transferred away from this process over any promise
     * communication channel.
     * @param object
     * @returns promise a wrapping of that object that
     * additionally responds to the "isDef" message
     * without a rejection.
     */
    Q.master = master;
    function master(object) {
        return Promise({
            "isDef": function isDef() {}
        }, function fallback(op, args) {
            return dispatch(object, op, args);
        }, function () {
            return Q(object).inspect();
        });
    }

    /**
     * Spreads the values of a promised array of arguments into the
     * fulfillment callback.
     * @param fulfilled callback that receives variadic arguments from the
     * promised array
     * @param rejected callback that receives the exception if the promise
     * is rejected.
     * @returns a promise for the return value or thrown exception of
     * either callback.
     */
    Q.spread = spread;
    function spread(value, fulfilled, rejected) {
        return Q(value).spread(fulfilled, rejected);
    }

    Promise.prototype.spread = function (fulfilled, rejected) {
        return this.all().then(function (array) {
            return fulfilled.apply(void 0, array);
        }, rejected);
    };

    /**
     * The async function is a decorator for generator functions, turning
     * them into asynchronous generators.  Although generators are only part
     * of the newest ECMAScript 6 drafts, this code does not cause syntax
     * errors in older engines.  This code should continue to work and will
     * in fact improve over time as the language improves.
     *
     * ES6 generators are currently part of V8 version 3.19 with the
     * --harmony-generators runtime flag enabled.  SpiderMonkey has had them
     * for longer, but under an older Python-inspired form.  This function
     * works on both kinds of generators.
     *
     * Decorates a generator function such that:
     *  - it may yield promises
     *  - execution will continue when that promise is fulfilled
     *  - the value of the yield expression will be the fulfilled value
     *  - it returns a promise for the return value (when the generator
     *    stops iterating)
     *  - the decorated function returns a promise for the return value
     *    of the generator or the first rejected promise among those
     *    yielded.
     *  - if an error is thrown in the generator, it propagates through
     *    every following yield until it is caught, or until it escapes
     *    the generator function altogether, and is translated into a
     *    rejection for the promise returned by the decorated generator.
     */
    Q.async = async;
    function async(makeGenerator) {
        return function () {
            // when verb is "send", arg is a value
            // when verb is "throw", arg is an exception
            function continuer(verb, arg) {
                var result;

                // Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only
                // engine that has a deployed base of browsers that support generators.
                // However, SM's generators use the Python-inspired semantics of
                // outdated ES6 drafts.  We would like to support ES6, but we'd also
                // like to make it possible to use generators in deployed browsers, so
                // we also support Python-style generators.  At some point we can remove
                // this block.

                if (typeof StopIteration === "undefined") {
                    // ES6 Generators
                    try {
                        result = generator[verb](arg);
                    } catch (exception) {
                        return reject(exception);
                    }
                    if (result.done) {
                        return Q(result.value);
                    } else {
                        return when(result.value, callback, errback);
                    }
                } else {
                    // SpiderMonkey Generators
                    // FIXME: Remove this case when SM does ES6 generators.
                    try {
                        result = generator[verb](arg);
                    } catch (exception) {
                        if (isStopIteration(exception)) {
                            return Q(exception.value);
                        } else {
                            return reject(exception);
                        }
                    }
                    return when(result, callback, errback);
                }
            }
            var generator = makeGenerator.apply(this, arguments);
            var callback = continuer.bind(continuer, "next");
            var errback = continuer.bind(continuer, "throw");
            return callback();
        };
    }

    /**
     * The spawn function is a small wrapper around async that immediately
     * calls the generator and also ends the promise chain, so that any
     * unhandled errors are thrown instead of forwarded to the error
     * handler. This is useful because it's extremely common to run
     * generators at the top-level to work with libraries.
     */
    Q.spawn = spawn;
    function spawn(makeGenerator) {
        Q.done(Q.async(makeGenerator)());
    }

    // FIXME: Remove this interface once ES6 generators are in SpiderMonkey.
    /**
     * Throws a ReturnValue exception to stop an asynchronous generator.
     *
     * This interface is a stop-gap measure to support generator return
     * values in older Firefox/SpiderMonkey.  In browsers that support ES6
     * generators like Chromium 29, just use "return" in your generator
     * functions.
     *
     * @param value the return value for the surrounding generator
     * @throws ReturnValue exception with the value.
     * @example
     * // ES6 style
     * Q.async(function* () {
     *      var foo = yield getFooPromise();
     *      var bar = yield getBarPromise();
     *      return foo + bar;
     * })
     * // Older SpiderMonkey style
     * Q.async(function () {
     *      var foo = yield getFooPromise();
     *      var bar = yield getBarPromise();
     *      Q.return(foo + bar);
     * })
     */
    Q["return"] = _return;
    function _return(value) {
        throw new QReturnValue(value);
    }

    /**
     * The promised function decorator ensures that any promise arguments
     * are settled and passed as values (`this` is also settled and passed
     * as a value).  It will also ensure that the result of a function is
     * always a promise.
     *
     * @example
     * var add = Q.promised(function (a, b) {
     *     return a + b;
     * });
     * add(Q(a), Q(B));
     *
     * @param {function} callback The function to decorate
     * @returns {function} a function that has been decorated.
     */
    Q.promised = promised;
    function promised(callback) {
        return function () {
            return spread([this, all(arguments)], function (self, args) {
                return callback.apply(self, args);
            });
        };
    }

    /**
     * sends a message to a value in a future turn
     * @param object* the recipient
     * @param op the name of the message operation, e.g., "when",
     * @param args further arguments to be forwarded to the operation
     * @returns result {Promise} a promise for the result of the operation
     */
    Q.dispatch = dispatch;
    function dispatch(object, op, args) {
        return Q(object).dispatch(op, args);
    }

    Promise.prototype.dispatch = function (op, args) {
        var self = this;
        var deferred = defer();
        Q.nextTick(function () {
            self.promiseDispatch(deferred.resolve, op, args);
        });
        return deferred.promise;
    };

    /**
     * Gets the value of a property in a future turn.
     * @param object    promise or immediate reference for target object
     * @param name      name of property to get
     * @return promise for the property value
     */
    Q.get = function (object, key) {
        return Q(object).dispatch("get", [key]);
    };

    Promise.prototype.get = function (key) {
        return this.dispatch("get", [key]);
    };

    /**
     * Sets the value of a property in a future turn.
     * @param object    promise or immediate reference for object object
     * @param name      name of property to set
     * @param value     new value of property
     * @return promise for the return value
     */
    Q.set = function (object, key, value) {
        return Q(object).dispatch("set", [key, value]);
    };

    Promise.prototype.set = function (key, value) {
        return this.dispatch("set", [key, value]);
    };

    /**
     * Deletes a property in a future turn.
     * @param object    promise or immediate reference for target object
     * @param name      name of property to delete
     * @return promise for the return value
     */
    Q.del = // XXX legacy
    Q["delete"] = function (object, key) {
        return Q(object).dispatch("delete", [key]);
    };

    Promise.prototype.del = // XXX legacy
    Promise.prototype["delete"] = function (key) {
        return this.dispatch("delete", [key]);
    };

    /**
     * Invokes a method in a future turn.
     * @param object    promise or immediate reference for target object
     * @param name      name of method to invoke
     * @param value     a value to post, typically an array of
     *                  invocation arguments for promises that
     *                  are ultimately backed with `resolve` values,
     *                  as opposed to those backed with URLs
     *                  wherein the posted value can be any
     *                  JSON serializable object.
     * @return promise for the return value
     */
    // bound locally because it is used by other methods
    Q.mapply = // XXX As proposed by "Redsandro"
    Q.post = function (object, name, args) {
        return Q(object).dispatch("post", [name, args]);
    };

    Promise.prototype.mapply = // XXX As proposed by "Redsandro"
    Promise.prototype.post = function (name, args) {
        return this.dispatch("post", [name, args]);
    };

    /**
     * Invokes a method in a future turn.
     * @param object    promise or immediate reference for target object
     * @param name      name of method to invoke
     * @param ...args   array of invocation arguments
     * @return promise for the return value
     */
    Q.send = // XXX Mark Miller's proposed parlance
    Q.mcall = // XXX As proposed by "Redsandro"
    Q.invoke = function (object, name /*...args*/) {
        return Q(object).dispatch("post", [name, array_slice(arguments, 2)]);
    };

    Promise.prototype.send = // XXX Mark Miller's proposed parlance
    Promise.prototype.mcall = // XXX As proposed by "Redsandro"
    Promise.prototype.invoke = function (name /*...args*/) {
        return this.dispatch("post", [name, array_slice(arguments, 1)]);
    };

    /**
     * Applies the promised function in a future turn.
     * @param object    promise or immediate reference for target function
     * @param args      array of application arguments
     */
    Q.fapply = function (object, args) {
        return Q(object).dispatch("apply", [void 0, args]);
    };

    Promise.prototype.fapply = function (args) {
        return this.dispatch("apply", [void 0, args]);
    };

    /**
     * Calls the promised function in a future turn.
     * @param object    promise or immediate reference for target function
     * @param ...args   array of application arguments
     */
    Q["try"] = Q.fcall = function (object /* ...args*/) {
        return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]);
    };

    Promise.prototype.fcall = function () /*...args*/{
        return this.dispatch("apply", [void 0, array_slice(arguments)]);
    };

    /**
     * Binds the promised function, transforming return values into a fulfilled
     * promise and thrown errors into a rejected one.
     * @param object    promise or immediate reference for target function
     * @param ...args   array of application arguments
     */
    Q.fbind = function (object /*...args*/) {
        var promise = Q(object);
        var args = array_slice(arguments, 1);
        return function fbound() {
            return promise.dispatch("apply", [this, args.concat(array_slice(arguments))]);
        };
    };
    Promise.prototype.fbind = function () /*...args*/{
        var promise = this;
        var args = array_slice(arguments);
        return function fbound() {
            return promise.dispatch("apply", [this, args.concat(array_slice(arguments))]);
        };
    };

    /**
     * Requests the names of the owned properties of a promised
     * object in a future turn.
     * @param object    promise or immediate reference for target object
     * @return promise for the keys of the eventually settled object
     */
    Q.keys = function (object) {
        return Q(object).dispatch("keys", []);
    };

    Promise.prototype.keys = function () {
        return this.dispatch("keys", []);
    };

    /**
     * Turns an array of promises into a promise for an array.  If any of
     * the promises gets rejected, the whole array is rejected immediately.
     * @param {Array*} an array (or promise for an array) of values (or
     * promises for values)
     * @returns a promise for an array of the corresponding values
     */
    // By Mark Miller
    // http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled
    Q.all = all;
    function all(promises) {
        return when(promises, function (promises) {
            var pendingCount = 0;
            var deferred = defer();
            array_reduce(promises, function (undefined, promise, index) {
                var snapshot;
                if (isPromise(promise) && (snapshot = promise.inspect()).state === "fulfilled") {
                    promises[index] = snapshot.value;
                } else {
                    ++pendingCount;
                    when(promise, function (value) {
                        promises[index] = value;
                        if (--pendingCount === 0) {
                            deferred.resolve(promises);
                        }
                    }, deferred.reject, function (progress) {
                        deferred.notify({ index: index, value: progress });
                    });
                }
            }, void 0);
            if (pendingCount === 0) {
                deferred.resolve(promises);
            }
            return deferred.promise;
        });
    }

    Promise.prototype.all = function () {
        return all(this);
    };

    /**
     * Returns the first resolved promise of an array. Prior rejected promises are
     * ignored.  Rejects only if all promises are rejected.
     * @param {Array*} an array containing values or promises for values
     * @returns a promise fulfilled with the value of the first resolved promise,
     * or a rejected promise if all promises are rejected.
     */
    Q.any = any;

    function any(promises) {
        if (promises.length === 0) {
            return Q.resolve();
        }

        var deferred = Q.defer();
        var pendingCount = 0;
        array_reduce(promises, function (prev, current, index) {
            var promise = promises[index];

            pendingCount++;

            when(promise, onFulfilled, onRejected, onProgress);
            function onFulfilled(result) {
                deferred.resolve(result);
            }
            function onRejected(err) {
                pendingCount--;
                if (pendingCount === 0) {
                    err.message = "Q can't get fulfillment value from any promise, all " + "promises were rejected. Last error message: " + err.message;
                    deferred.reject(err);
                }
            }
            function onProgress(progress) {
                deferred.notify({
                    index: index,
                    value: progress
                });
            }
        }, undefined);

        return deferred.promise;
    }

    Promise.prototype.any = function () {
        return any(this);
    };

    /**
     * Waits for all promises to be settled, either fulfilled or
     * rejected.  This is distinct from `all` since that would stop
     * waiting at the first rejection.  The promise returned by
     * `allResolved` will never be rejected.
     * @param promises a promise for an array (or an array) of promises
     * (or values)
     * @return a promise for an array of promises
     */
    Q.allResolved = deprecate(allResolved, "allResolved", "allSettled");
    function allResolved(promises) {
        return when(promises, function (promises) {
            promises = array_map(promises, Q);
            return when(all(array_map(promises, function (promise) {
                return when(promise, noop, noop);
            })), function () {
                return promises;
            });
        });
    }

    Promise.prototype.allResolved = function () {
        return allResolved(this);
    };

    /**
     * @see Promise#allSettled
     */
    Q.allSettled = allSettled;
    function allSettled(promises) {
        return Q(promises).allSettled();
    }

    /**
     * Turns an array of promises into a promise for an array of their states (as
     * returned by `inspect`) when they have all settled.
     * @param {Array[Any*]} values an array (or promise for an array) of values (or
     * promises for values)
     * @returns {Array[State]} an array of states for the respective values.
     */
    Promise.prototype.allSettled = function () {
        return this.then(function (promises) {
            return all(array_map(promises, function (promise) {
                promise = Q(promise);
                function regardless() {
                    return promise.inspect();
                }
                return promise.then(regardless, regardless);
            }));
        });
    };

    /**
     * Captures the failure of a promise, giving an oportunity to recover
     * with a callback.  If the given promise is fulfilled, the returned
     * promise is fulfilled.
     * @param {Any*} promise for something
     * @param {Function} callback to fulfill the returned promise if the
     * given promise is rejected
     * @returns a promise for the return value of the callback
     */
    Q.fail = // XXX legacy
    Q["catch"] = function (object, rejected) {
        return Q(object).then(void 0, rejected);
    };

    Promise.prototype.fail = // XXX legacy
    Promise.prototype["catch"] = function (rejected) {
        return this.then(void 0, rejected);
    };

    /**
     * Attaches a listener that can respond to progress notifications from a
     * promise's originating deferred. This listener receives the exact arguments
     * passed to ``deferred.notify``.
     * @param {Any*} promise for something
     * @param {Function} callback to receive any progress notifications
     * @returns the given promise, unchanged
     */
    Q.progress = progress;
    function progress(object, progressed) {
        return Q(object).then(void 0, void 0, progressed);
    }

    Promise.prototype.progress = function (progressed) {
        return this.then(void 0, void 0, progressed);
    };

    /**
     * Provides an opportunity to observe the settling of a promise,
     * regardless of whether the promise is fulfilled or rejected.  Forwards
     * the resolution to the returned promise when the callback is done.
     * The callback can return a promise to defer completion.
     * @param {Any*} promise
     * @param {Function} callback to observe the resolution of the given
     * promise, takes no arguments.
     * @returns a promise for the resolution of the given promise when
     * ``fin`` is done.
     */
    Q.fin = // XXX legacy
    Q["finally"] = function (object, callback) {
        return Q(object)["finally"](callback);
    };

    Promise.prototype.fin = // XXX legacy
    Promise.prototype["finally"] = function (callback) {
        if (!callback || typeof callback.apply !== "function") {
            throw new Error("Q can't apply finally callback");
        }
        callback = Q(callback);
        return this.then(function (value) {
            return callback.fcall().then(function () {
                return value;
            });
        }, function (reason) {
            // TODO attempt to recycle the rejection with "this".
            return callback.fcall().then(function () {
                throw reason;
            });
        });
    };

    /**
     * Terminates a chain of promises, forcing rejections to be
     * thrown as exceptions.
     * @param {Any*} promise at the end of a chain of promises
     * @returns nothing
     */
    Q.done = function (object, fulfilled, rejected, progress) {
        return Q(object).done(fulfilled, rejected, progress);
    };

    Promise.prototype.done = function (fulfilled, rejected, progress) {
        var onUnhandledError = function onUnhandledError(error) {
            // forward to a future turn so that ``when``
            // does not catch it and turn it into a rejection.
            Q.nextTick(function () {
                makeStackTraceLong(error, promise);
                if (Q.onerror) {
                    Q.onerror(error);
                } else {
                    throw error;
                }
            });
        };

        // Avoid unnecessary `nextTick`ing via an unnecessary `when`.
        var promise = fulfilled || rejected || progress ? this.then(fulfilled, rejected, progress) : this;

        if ((typeof process === "undefined" ? "undefined" : _typeof(process)) === "object" && process && process.domain) {
            onUnhandledError = process.domain.bind(onUnhandledError);
        }

        promise.then(void 0, onUnhandledError);
    };

    /**
     * Causes a promise to be rejected if it does not get fulfilled before
     * some milliseconds time out.
     * @param {Any*} promise
     * @param {Number} milliseconds timeout
     * @param {Any*} custom error message or Error object (optional)
     * @returns a promise for the resolution of the given promise if it is
     * fulfilled before the timeout, otherwise rejected.
     */
    Q.timeout = function (object, ms, error) {
        return Q(object).timeout(ms, error);
    };

    Promise.prototype.timeout = function (ms, error) {
        var deferred = defer();
        var timeoutId = setTimeout(function () {
            if (!error || "string" === typeof error) {
                error = new Error(error || "Timed out after " + ms + " ms");
                error.code = "ETIMEDOUT";
            }
            deferred.reject(error);
        }, ms);

        this.then(function (value) {
            clearTimeout(timeoutId);
            deferred.resolve(value);
        }, function (exception) {
            clearTimeout(timeoutId);
            deferred.reject(exception);
        }, deferred.notify);

        return deferred.promise;
    };

    /**
     * Returns a promise for the given value (or promised value), some
     * milliseconds after it resolved. Passes rejections immediately.
     * @param {Any*} promise
     * @param {Number} milliseconds
     * @returns a promise for the resolution of the given promise after milliseconds
     * time has elapsed since the resolution of the given promise.
     * If the given promise rejects, that is passed immediately.
     */
    Q.delay = function (object, timeout) {
        if (timeout === void 0) {
            timeout = object;
            object = void 0;
        }
        return Q(object).delay(timeout);
    };

    Promise.prototype.delay = function (timeout) {
        return this.then(function (value) {
            var deferred = defer();
            setTimeout(function () {
                deferred.resolve(value);
            }, timeout);
            return deferred.promise;
        });
    };

    /**
     * Passes a continuation to a Node function, which is called with the given
     * arguments provided as an array, and returns a promise.
     *
     *      Q.nfapply(FS.readFile, [__filename])
     *      .then(function (content) {
     *      })
     *
     */
    Q.nfapply = function (callback, args) {
        return Q(callback).nfapply(args);
    };

    Promise.prototype.nfapply = function (args) {
        var deferred = defer();
        var nodeArgs = array_slice(args);
        nodeArgs.push(deferred.makeNodeResolver());
        this.fapply(nodeArgs).fail(deferred.reject);
        return deferred.promise;
    };

    /**
     * Passes a continuation to a Node function, which is called with the given
     * arguments provided individually, and returns a promise.
     * @example
     * Q.nfcall(FS.readFile, __filename)
     * .then(function (content) {
     * })
     *
     */
    Q.nfcall = function (callback /*...args*/) {
        var args = array_slice(arguments, 1);
        return Q(callback).nfapply(args);
    };

    Promise.prototype.nfcall = function () /*...args*/{
        var nodeArgs = array_slice(arguments);
        var deferred = defer();
        nodeArgs.push(deferred.makeNodeResolver());
        this.fapply(nodeArgs).fail(deferred.reject);
        return deferred.promise;
    };

    /**
     * Wraps a NodeJS continuation passing function and returns an equivalent
     * version that returns a promise.
     * @example
     * Q.nfbind(FS.readFile, __filename)("utf-8")
     * .then(console.log)
     * .done()
     */
    Q.nfbind = Q.denodeify = function (callback /*...args*/) {
        if (callback === undefined) {
            throw new Error("Q can't wrap an undefined function");
        }
        var baseArgs = array_slice(arguments, 1);
        return function () {
            var nodeArgs = baseArgs.concat(array_slice(arguments));
            var deferred = defer();
            nodeArgs.push(deferred.makeNodeResolver());
            Q(callback).fapply(nodeArgs).fail(deferred.reject);
            return deferred.promise;
        };
    };

    Promise.prototype.nfbind = Promise.prototype.denodeify = function () /*...args*/{
        var args = array_slice(arguments);
        args.unshift(this);
        return Q.denodeify.apply(void 0, args);
    };

    Q.nbind = function (callback, thisp /*...args*/) {
        var baseArgs = array_slice(arguments, 2);
        return function () {
            var nodeArgs = baseArgs.concat(array_slice(arguments));
            var deferred = defer();
            nodeArgs.push(deferred.makeNodeResolver());
            function bound() {
                return callback.apply(thisp, arguments);
            }
            Q(bound).fapply(nodeArgs).fail(deferred.reject);
            return deferred.promise;
        };
    };

    Promise.prototype.nbind = function () /*thisp, ...args*/{
        var args = array_slice(arguments, 0);
        args.unshift(this);
        return Q.nbind.apply(void 0, args);
    };

    /**
     * Calls a method of a Node-style object that accepts a Node-style
     * callback with a given array of arguments, plus a provided callback.
     * @param object an object that has the named method
     * @param {String} name name of the method of object
     * @param {Array} args arguments to pass to the method; the callback
     * will be provided by Q and appended to these arguments.
     * @returns a promise for the value or error
     */
    Q.nmapply = // XXX As proposed by "Redsandro"
    Q.npost = function (object, name, args) {
        return Q(object).npost(name, args);
    };

    Promise.prototype.nmapply = // XXX As proposed by "Redsandro"
    Promise.prototype.npost = function (name, args) {
        var nodeArgs = array_slice(args || []);
        var deferred = defer();
        nodeArgs.push(deferred.makeNodeResolver());
        this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
        return deferred.promise;
    };

    /**
     * Calls a method of a Node-style object that accepts a Node-style
     * callback, forwarding the given variadic arguments, plus a provided
     * callback argument.
     * @param object an object that has the named method
     * @param {String} name name of the method of object
     * @param ...args arguments to pass to the method; the callback will
     * be provided by Q and appended to these arguments.
     * @returns a promise for the value or error
     */
    Q.nsend = // XXX Based on Mark Miller's proposed "send"
    Q.nmcall = // XXX Based on "Redsandro's" proposal
    Q.ninvoke = function (object, name /*...args*/) {
        var nodeArgs = array_slice(arguments, 2);
        var deferred = defer();
        nodeArgs.push(deferred.makeNodeResolver());
        Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject);
        return deferred.promise;
    };

    Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send"
    Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal
    Promise.prototype.ninvoke = function (name /*...args*/) {
        var nodeArgs = array_slice(arguments, 1);
        var deferred = defer();
        nodeArgs.push(deferred.makeNodeResolver());
        this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
        return deferred.promise;
    };

    /**
     * If a function would like to support both Node continuation-passing-style and
     * promise-returning-style, it can end its internal promise chain with
     * `nodeify(nodeback)`, forwarding the optional nodeback argument.  If the user
     * elects to use a nodeback, the result will be sent there.  If they do not
     * pass a nodeback, they will receive the result promise.
     * @param object a result (or a promise for a result)
     * @param {Function} nodeback a Node.js-style callback
     * @returns either the promise or nothing
     */
    Q.nodeify = nodeify;
    function nodeify(object, nodeback) {
        return Q(object).nodeify(nodeback);
    }

    Promise.prototype.nodeify = function (nodeback) {
        if (nodeback) {
            this.then(function (value) {
                Q.nextTick(function () {
                    nodeback(null, value);
                });
            }, function (error) {
                Q.nextTick(function () {
                    nodeback(error);
                });
            });
        } else {
            return this;
        }
    };

    Q.noConflict = function () {
        throw new Error("Q.noConflict only works when Q is used as a global");
    };

    // All code before this point will be filtered from stack traces.
    var qEndingLine = captureLine();

    return Q;
}); 
 			}); 		define("utils/trial-core.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

var T = require("util");
var api = require("api");
var insureConfig = require("insure-config");
var moment = require('moment');
moment.locale('zh-cn');

var opt,
    _lastTrialItem,
    _trialAttr = {},
    _renderData = [],
    _resultData = {};
var _product = {},
    _insureModule = {},
    _insureSort = [],
    _insureBeneficiaryType = 1,
    _insurantTypeArray,
    _insureData = {},
    _startDate,
    _supportSelf = false,
    _supportOther = false,
    _supportMore = false,
    _supportMono = false,
    _supportAppoint = false,
    _ifSelf = false,
    _ifLegal = false;

var processing = false;

var Trial = {
    config: function config(options) {
        opt = options || {};
        Trial.callback = opt.callback;
        Trial.init();
    },
    init: function init() {
        if (opt.trialGenes) {
            Trial.initTrailAttr(opt.trialGenes.genes);
        }
        Trial.requestTrial();
    },
    getPartnerId: function getPartnerId() {
        return opt.uid;
    },
    getProductId: function getProductId() {
        return opt.productId;
    },
    getPlanId: function getPlanId() {
        return opt.planId;
    },
    getTrialVal: function getTrialVal(key) {
        return _trialAttr[key] || {};
    }, //获取试算因子的值
    setTrialVal: function setTrialVal(key, val) {
        _lastTrialItem = T.clone(_trialAttr[key]);
        _trialAttr[key].value = val;
    }, //设置试算因子
    tryTrialPrice: function tryTrialPrice(cb) {
        Trial.requestTrial(cb);
    }, //进行试算
    getTrialGenes: function getTrialGenes() {
        var params = [];
        for (var i in _trialAttr) {
            params.push(_trialAttr[i]);
        }
        return JSON.stringify({
            productId: opt.productId,
            productPlanId: opt.planId,
            "genes": params
        });
    }, //获取试算因子
    getTrialPrice: function getTrialPrice() {
        return _resultData.preminum;
    }, //获取试算价格
    getTrialItem: function getTrialItem(key) {
        var result = {};
        T.each(T.isEmpty(_resultData.restrictGenes) ? _resultData.restrictGenesOld : _resultData.restrictGenes, function (item, i) {
            var b = item.key || item.geneKey;
            if (key == b) {
                result = item;
            }
        });
        return result;
    }, //获取某个试算项目具体内容
    getProtectItem: function getProtectItem() {
        var trialItemLst = _resultData.protectTrialItemList;
        var protectItemLst = [];
        T.each(trialItemLst, function (trialItem, index) {
            if (T.isUndefined(trialItem.relateCoverageId)) {
                if (trialItem.display) {
                    protectItemLst.push({
                        name: trialItem.name,
                        value: trialItem.fullPremium,
                        description: trialItem.description,
                        id: trialItem.id
                    });
                }
            } else {
                var item = Trial.getTrialItem(trialItem.relateCoverageId);
                var dataList = [];
                if (item.controlType == 0) {
                    T.each(item.dictionaryList, function (sub) {
                        if (sub.type == 0 || sub.type == 1) {
                            dataList.push(sub.value + Trial.transUnit(sub.unit));
                        } else if (sub.type == 2) {
                            var min = sub.min;
                            var max = sub.max;
                            var step = sub.step;
                            var tmp = min;
                            for (; tmp <= max; tmp += step) {
                                dataList.push(tmp + Trial.transUnit(sub.unit));
                            }
                            if (tmp < max) {
                                dataList.push(max + Trial.transUnit(sub.unit));
                            }
                        }
                    });
                }
                if (trialItem.display) {
                    protectItemLst.push({
                        name: trialItem.name,
                        value: Trial.getTrialGenesMap()[trialItem.relateCoverageId].value,
                        description: trialItem.description,
                        dataList: dataList,
                        id: trialItem.relateCoverageId
                    });
                }
            }
        });
        return protectItemLst;
    }, //获取保障项目
    getTrialGenesMap: function getTrialGenesMap() {
        var params = {};
        for (var i in _trialAttr) {
            var key = _trialAttr[i].key ? _trialAttr[i].key : _trialAttr[i].protectItemId;
            params[key] = _trialAttr[i];
        }
        return params;
    },
    getResultData: function getResultData() {
        return _resultData;
    }, //获取getTrial请求的结果
    transUnit: function transUnit(unit) {
        return {
            0: '',
            1: '份',
            2: '万元',
            3: '元',
            4: '0元',
            5: '00元',
            6: '000元',
            7: '岁',
            8: '年',
            9: '月',
            10: '天',
            11: '元/年',
            12: '',
            13: '周岁'
        }[unit];
    }, //获取单位
    calculateInsurantDateInDetail: function calculateInsurantDateInDetail(product) {
        var insureDate = moment(Trial.now());
        var insureTime = product.insureTime; //起保时间：1可选起保日期，2固定起保日期，3起保日期为出单日期
        if (insureTime == 1) {
            var firstDate = product.firstDate;
            var deadline = product.deadline;
            var nextDayDeadline = product.nextDayDeadline;
            if (firstDate == 0) {
                //当天起保
                if (insureDate.isAfter(moment(deadline, "HH:mm"))) {
                    insureDate.add(1, "d");
                }
            } else {
                if (insureDate.isAfter(moment(nextDayDeadline, "HH:mm"))) {
                    insureDate.add(1 + firstDate, "d");
                } else {
                    insureDate.add(firstDate, "d");
                }
            }
        }
        return Trial.getInsureDate(insureDate, product);
    }, //获取产品详情试算时，被保险人生日范围
    calculateInsurantDateSubrestrict: function calculateInsurantDateSubrestrict(dateLimit) {
        var insurantDate = Trial.getTrialItem("insurantDate");
        if (dateLimit.minDate && insurantDate.controlType == 1 && insurantDate.dictionaryList.length > 0) {
            var subrestrict = insurantDate.dictionaryList[0].subrestrict;
            var condition = subrestrict.condition;
            var max = subrestrict.max;
            if (condition == 0) {
                dateLimit.maxDate.add(max + 1, 'd');
            } else if (condition == 1) {
                dateLimit.maxDate.add(max, 'd');
            }
        }
        return dateLimit;
    },

    /**
     *
     * @param insureDate  起保日期（yyyy-MM-dd）
     * @param product 产品基础配置信息
     * @returns {{minDate: *, maxDate: *}}
     */
    getInsureDate: function getInsureDate(insureDate, product) {
        var minLimit = -1,
            maxLimit = -1,
            unit,
            timestamp = this.now(),
            insuredAgeCalculation = product.insuredAgeCalculation,
            //被保人年龄计算方式：1=起保日期 2=投保日期
        insureIncludeBirthday = product.insureIncludeBirthday; //保费计算是否包含生日当天：0是 1否(同月同日算一年)(这也是一个坑)
        T.each(this.getTrialItem('insurantDate').dictionaryList, function (item, i) {
            if (minLimit == -1 || maxLimit == -1) {
                minLimit = item.max;
                maxLimit = item.min;
                unit = item.unit;
            } else if (item.max > minLimit) {
                minLimit = item.max;
            } else if (item.min > maxLimit) {
                maxLimit = item.min;
            }
        });
        var minDate = moment(timestamp);
        var maxDate = moment(timestamp);

        if (insuredAgeCalculation == 1) {
            if (insureDate) {
                console.log('被保人年龄计算方式为起保时间');
                minDate = moment(insureDate);
                maxDate = moment(insureDate);
            } else {
                console.log('被保人年龄计算方式为投保时间');
                return;
            }
        }
        if (!this.getTrialItem('insurantDate').dictionaryList) {
            minDate.subtract(120, 'y');
        } else {
            if (!insureIncludeBirthday) {
                console.log('同年同月同日算0岁');
                maxDate.subtract(1, 'd');
            } else {
                console.log('同年同月同日算1岁');
                minDate.add(1, 'd');
            }
            if (unit == 7 || unit == 8 || unit == 13) {
                minDate.subtract(minLimit + 1, 'y');
                //minDate.add(1, 'd');
                maxDate.subtract(maxLimit, 'y');
            } else if (unit == 9) {
                minDate.subtract(minLimit, 'M');
                maxDate.subtract(maxLimit, 'M');
            } else if (unit == 10) {
                minDate.subtract(minLimit, 'd');
                maxDate.subtract(maxLimit, 'd');
            } else {
                minDate.subtract(120, 'y');
            }
        }

        return {
            minDate: minDate,
            maxDate: maxDate
        };
    },
    initTrailAttr: function initTrailAttr(genes) {
        genes = genes || [];
        _renderData = [];
        T.each(genes, function (item, i) {
            var key = item.key ? item.key : item.protectItemId;
            _trialAttr[key] = {
                "sort": item.sort,
                "protectItemId": item.protectItemId ? item.protectItemId : '',
                "key": item.key ? item.key : '',
                "value": item.value ? item.value : item.defaultValue
            };
            if (item.subRestrictGeneList) {
                T.each(item.subRestrictGeneList, function (subItem, index) {
                    var subKey = subItem.key ? subItem.key : subItem.protectItemId;
                    _trialAttr[subKey] = {
                        "sort": subItem.sort,
                        "protectItemId": subItem.protectItemId ? subItem.protectItemId : '',
                        "key": subItem.key ? subItem.key : '',
                        "value": subItem.value ? subItem.value : subItem.defaultValue
                    };
                });
            }
            if (item.display) {
                _renderData.push(item);
            }
        });
    },
    requestTrial: function requestTrial(cb) {
        if (T.isEmpty(_trialAttr)) {
            api.getTrial({
                data: {
                    prodId: opt.productId,
                    planId: opt.planId,
                    uid: opt.uid
                },
                success: function success(result) {
                    var err;
                    if (result.data.noticeMsg) err = {
                        msg: result.data.noticeMsg
                    };

                    console.log('产品标识', result.data.productId, result.data.planId, result.data.baseProductId, result.data.baseProductPlanId);
                    console.log('试算因子', result.data.restrictGenes);
                    console.log('保障项目', result.data.protectTrialItemList);
                    console.log('试算排版', result.data.trialLayoutItemList);
                    console.log('价格', result.data.preminum);

                    _resultData = result.data;
                    Trial.initTrailAttr(_resultData.restrictGenes);

                    opt.ready && opt.ready(err, {
                        productId: _resultData.productId,
                        productName: _resultData.productName,
                        planId: _resultData.productPlanId,
                        planName: _resultData.planName,
                        planList: _resultData.planLst,
                        geneList: _renderData,
                        geneLayout: _resultData.trialLayoutItemList,
                        protectItemList: _resultData.protectTrialItemList,
                        price: _resultData.preminum,
                        planCount: _resultData.planCount,
                        partnerFee: _resultData.partnerFee,
                        discountFee: _resultData.discountFee
                    });
                }
            });

            if (Trial.callback && Trial.callback.renderInsureAttr) {
                Trial.configInsure && Trial.configInsure();
            }
        } else {
            var params = [];
            for (var i in _trialAttr) {
                params.push(_trialAttr[i]);
            }
            var genes = {
                productId: opt.productId,
                productPlanId: opt.planId,
                genes: params
            };
            if (_lastTrialItem) genes.optGeneOldValue = _lastTrialItem;
            var trialReq = {
                uid: opt.uid,
                prodId: opt.productId,
                planId: opt.planId,
                restrictGeneParams: JSON.stringify(genes)
            };
            api.tryTrial({
                data: trialReq,
                success: function success(result) {
                    if (!result.success) {
                        opt.onChange && opt.onChange({ msg: result.msg });
                        return;
                    }
                    console.log('产品标识', result.data.productId, result.data.productPlanId, result.data.baseProductId, result.data.baseProductPlanId);
                    var err;
                    if (result.data.noticeMsg) err = {
                        msg: result.data.noticeMsg
                    };

                    if (Trial.callback && Trial.callback.renderInsureAttr) {
                        Trial.configInsure && Trial.configInsure();
                    }

                    if (result.data.restrictGenes) {
                        /**
                         * 下面是一个坑，不要随便改
                         */
                        var oldGenes, newGenes;
                        newGenes = result.data.restrictGenes;
                        if (T.isEmpty(_resultData.restrictGenes)) oldGenes = _resultData.restrictGenesOld;else oldGenes = _resultData.restrictGenes;
                        var protectItemTmp = _resultData.protectTrialItemList;
                        _resultData = T.clone(result.data);
                        _resultData.restrictGenesOld = oldGenes;

                        //接口只返回改变的值，如果有改变的则按照KEY遍历赋值
                        if (!T.isEmpty(result.data.restrictGenes) && !T.isEmpty(oldGenes)) {
                            _resultData.restrictGenes = T.clone(oldGenes);
                            T.each(result.data.restrictGenes, function (genesNew, i) {
                                if (genesNew.key) {
                                    _trialAttr[genesNew.key].value = genesNew.defaultValue;
                                } else if (genesNew.geneKey) {
                                    _trialAttr[genesNew.geneKey].value = genesNew.defaultValue;
                                }
                                T.each(_resultData.restrictGenes, function (genesOld, j) {
                                    if (genesNew.key && genesNew.key == genesOld.key || genesNew.geneKey && genesNew.geneKey == genesOld.geneKey) {
                                        _resultData.restrictGenes[j] = genesNew;
                                    }
                                });
                            });
                        }
                        /**
                         * 这是坑的结尾
                         */

                        //保障项改变才会返回（改变之后不是返回改变后的全部，是返回改变的对应项）
                        T.each(result.data.protectTrialItemList, function (item, i) {
                            T.each(protectItemTmp, function (tmpItem, j) {
                                if (item.id == tmpItem.id) {
                                    protectItemTmp[j] = item;
                                }
                            });
                        });

                        if (!T.isUndefined(protectItemTmp)) {
                            _resultData.protectTrialItemList = protectItemTmp;
                        }
                        cb && cb(newGenes);
                        opt.onChange && opt.onChange(err, {
                            geneList: newGenes,
                            protectItemList: _resultData.protectTrialItemList,
                            price: _resultData.preminum,
                            planCount: _resultData.planCount,
                            partnerFee: _resultData.partnerFee,
                            discountFee: _resultData.discountFee
                        });
                    }
                }
            });
        }
    },
    now: function now() {
        return new Date().getTime();
    },

    configInsure: function configInsure() {
        //初始化投保
        api.insureAttr({
            showLoading: true,
            data: {
                prodId: opt.productId,
                planId: opt.planId
            },
            success: function success(result) {
                if (result.code === 0) {
                    var data;

                    var _optionalInsure;

                    (function () {
                        var parseInsureAttr = function parseInsureAttr(module, productAttrs) {
                            var attr = {};
                            var required = false;
                            var attrSort = [];
                            T.each(productAttrs, function (subItem, i) {
                                attrSort.push(subItem.attribute.keyCode);
                                attr[subItem.attribute.keyCode] = {
                                    id: subItem.attribute.id,
                                    keyCode: subItem.attribute.keyCode,
                                    name: subItem.attribute.name,
                                    type: subItem.attribute.type,
                                    required: subItem.required,
                                    regex: subItem.attribute.regex,
                                    defaultRemind: subItem.attribute.defaultRemind,
                                    errorRemind: subItem.attribute.errorRemind,
                                    sort: subItem.attribute.sort,
                                    values: subItem.attribute.values,
                                    restricts: []
                                };

                                if (subItem.required != 0) required = true;
                            });
                            module.required = required;
                            return [attr, attrSort];
                        };

                        var parseInsureRestrict = function parseInsureRestrict(item) {
                            var attr = {};
                            if (item.results[0].moduleId == 20) {
                                attr = _insureModule[item.results[0].moduleId].attr['default'];
                            } else if (item.results[0].moduleId == 30) {
                                attr = _insureModule[item.results[0].moduleId].attr.appoint;
                            } else {
                                attr = _insureModule[item.results[0].moduleId] ? _insureModule[item.results[0].moduleId].attr : {};
                            }
                            if (T.isEmpty(item.executes)) {
                                if (attr[item.results[0].keyCode]) {
                                    attr[item.results[0].keyCode].restricts.push({
                                        conditions: item.results[0].conditions,
                                        value: item.results[0].value,
                                        unit: item.results[0].unit
                                    });
                                }
                                if (item.results[0].moduleId == 20) {
                                    if (_insureModule[item.results[0].moduleId].attr['self'] && _insureModule[item.results[0].moduleId].attr['self'][item.results[0].keyCode]) _insureModule[item.results[0].moduleId].attr['self'][item.results[0].keyCode].restricts.push({
                                        conditions: item.results[0].conditions,
                                        value: item.results[0].value,
                                        unit: item.results[0].unit
                                    });
                                }
                            } else {
                                if (item.executes[0] && attr[item.executes[0].keyCode]) {
                                    attr[item.executes[0].keyCode].restricts.push({
                                        conditions: item.executes[0].conditions,
                                        value: item.executes[0].value,
                                        unit: item.executes[0].unit,
                                        target: {
                                            conditions: item.results[0].conditions,
                                            value: item.results[0].value,
                                            unit: item.results[0].unit
                                        }
                                    });
                                }
                            }
                        };

                        data = result.data || {};

                        _product = data.product;
                        _insureBeneficiaryType = _product.beneficiaryType == 1 || _product.beneficiaryType == 12 ? 1 : 2;
                        _insurantTypeArray = _product.insurantType.split(',');
                        _supportSelf = _insurantTypeArray[0] == '1';
                        _supportOther = _insurantTypeArray[1] == '1';
                        _supportMore = _insurantTypeArray[2] == '1';
                        _supportMono = _insurantTypeArray[3] == '1';
                        _supportAppoint = _product.beneficiaryType != 1 && _product.beneficiaryType != 0;

                        _ifSelf = _supportSelf;
                        _insureSort = [];

                        _optionalInsure = [];

                        T.each(data.modules, function (item, i) {
                            var module = {
                                id: item.id,
                                name: item.name,
                                sort: item.sort,
                                remark: item.remark,
                                attr: {}
                            };
                            if (_product.insureTime == 3 && item.id === 102) {
                                return;
                            }

                            var attrResult = parseInsureAttr(module, item.productAttrs);
                            if (item.id === 20) {
                                _insureData[item.id + '_self'] = [{}];
                                _insureData[item.id + '_default'] = [{}];
                                _insureData[item.id + '_mono'] = [];

                                var selfAttr = parseInsureAttr(module, item.selfProductAttrs);
                                module.attr['default'] = attrResult[0];
                                module.attr["self"] = selfAttr[0];

                                module.selfSort = selfAttr[1];
                                module.attrSort = attrResult[1];
                            } else if (item.id == 30) {
                                _insureData[item.id + '_appoint'] = [{}];
                                module.attr['appoint'] = attrResult[0];
                                module.attrSort = attrResult[1];
                            } else {
                                _insureData[item.id] = [{}];

                                module.attr = attrResult[0];
                                module.attrSort = attrResult[1];
                            }

                            _insureModule[item.id] = module;
                            if (item.id === 102) {
                                _insureSort.splice(0, 0, 102);
                            } else if (module.required == false && module.id != 20) {
                                _optionalInsure.push(item.id);
                            } else {
                                _insureSort.push(item.id);
                            }
                        });

                        T.each(_optionalInsure, function (item, i) {
                            _insureSort.push(item);
                        });

                        T.each(data.restricts, function (item, i) {
                            parseInsureRestrict(item);
                        });
                        console.log("insureAttr结果：", data);
                        data = {};

                        Trial.callback && Trial.callback.renderInsureAttr && Trial.callback.renderInsureAttr(null, _product, _insureModule, _insureSort);
                    })();
                }
            }
        });
    },
    setStartDate: function setStartDate(date) {
        _startDate = date;
    },
    getStartDate: function getStartDate() {
        return _startDate;
    },
    getInsureModule: function getInsureModule() {

        return _insureModule;
    },
    procInsurantBirthdateRestricts: function procInsurantBirthdateRestricts(values, birthdate) {
        if (!_supportSelf) {
            //不支持本人投保，被保人关系剔除本人
            for (var i = 0; i < values.length; i++) {
                if (values[i].controlValue == 1) {
                    values.splice(i, 1);
                    break;
                }
            }
        }
        if (birthdate) {
            var adultTime,
                array = [],
                insureDate = _startDate ? _startDate : T.formatDate("yyyy-MM-dd", Trial.now());
            if (!insureDate && _product.insureTime == 1) {
                T.showTips('请先选择起保日期');
                return;
            }
            var insuredAgeCalculation = _product.insuredAgeCalculation,
                //被保人年龄计算方式：1=起保日期 2=投保日期
            insureIncludeBirthday = _product.insureIncludeBirthday; //保费计算是否包含生日当天：0是 1否(同月同日算一年)(这也是一个坑)
            if (insuredAgeCalculation == 1) adultTime = moment(insureDate);else adultTime = moment(Trial.now());
            //if (insureIncludeBirthday == 0)
            //    adultTime.subtract(1, 'd');
            //else
            if (insureIncludeBirthday == 1) adultTime.add(1, 'd');
            var bool = moment(birthdate).add(18, 'y').isBefore(T.formatDate("yyyy-MM-dd", adultTime));
            // 未成年
            if (!bool) {
                /** 如果被保险人为未成年人，是否限制投保人只能为其父母或法定监护人 1是 0否 */
                if (_product.isInsurantJuveniles == 1) {
                    T.each(values, function (subItemVal, k) {
                        if (subItemVal.controlValue == 6 || subItemVal.controlValue == 7 || subItemVal.controlValue == 22) {
                            array.push(subItemVal);
                        }
                    });
                } else {
                    return values;
                }
            }
            // 成年
            else {
                    /** 如果被保险人为成年人，是否限制投保人只能为本人： 1是 0否 */
                    if (_product.isInsurantAdult == 1) {
                        T.each(values, function (subItemVal, k) {
                            if (subItemVal.controlValue == 1) {
                                array.push(subItemVal);
                            }
                        });
                    } else {
                        return values;
                    }
                }
            return array;
        } else {
            return values;
        }
    },
    procDateRrestricts: function procDateRrestricts(dateLimit, restricts) {
        if (restricts.length == 0) return dateLimit;
        var insureDateTime = moment(dateLimit.maxDate);
        var maxDate = moment(dateLimit.maxDate),
            minDate = moment(dateLimit.minDate),
            tmpMax,
            tmpMin;
        T.each(restricts.restricts, function (item, j) {
            // 0大于
            if (item.conditions == 0) {
                var dateUnit = Trial.transDateUnit(item.unit);
                tmpMax = insureDateTime.subtract(item.value, dateUnit).subtract(1, dateUnit);
                if (tmpMax.isBefore(maxDate)) maxDate = tmpMax;
            }
            // 1大于等于
            if (item.conditions == 1) {
                //tmpMax = insureDateTime.subtract(item.value, Trial.transDateUnit(item.unit)).add(1, 'd');
                tmpMax = insureDateTime.subtract(item.value, Trial.transDateUnit(item.unit));
                if (tmpMax.isBefore(maxDate)) maxDate = tmpMax;
            }
            // 2小于
            if (item.conditions == 2) {
                var dateUnit = Trial.transDateUnit(item.unit);
                tmpMin = insureDateTime.subtract(item.value, dateUnit).subtract(1, dateUnit);
                if (tmpMin.isAfter(minDate)) minDate = tmpMin;
            }
            // 3小于等于
            if (item.conditions == 3) {
                //tmpMin = insureDateTime.subtract(item.value, Trial.transDateUnit(item.unit)).add(1, 'd');
                tmpMin = insureDateTime.subtract(item.value, Trial.transDateUnit(item.unit));
                if (tmpMin.isAfter(minDate)) minDate = tmpMin;
            }
        });
        return {
            maxDate: maxDate,
            minDate: minDate
        };
    },
    procRestricts: function procRestricts(values, restricts) {
        if (restricts.length == 0) return values;
        var array = [];
        T.each(restricts, function (item, j) {
            if (item.target) return;
            var ar = [];
            T.each(values, function (subItem, i) {
                var vals = item.value.split(',');
                // 0大于
                if (item.conditions == 0) {
                    if (subItem.controlValue > T.max(vals)) {
                        ar.push(subItem);
                    }
                }
                // 1大于等于
                if (item.conditions == 1) {
                    if (subItem.controlValue >= T.max(vals)) {
                        ar.push(subItem);
                    }
                }
                // 2小于
                if (item.conditions == 2) {
                    if (subItem.controlValue < T.min(vals)) {
                        ar.push(subItem);
                    }
                }
                // 3小于等于
                if (item.conditions == 3) {
                    if (subItem.controlValue <= T.min(vals)) {
                        ar.push(subItem);
                    }
                }
                // 4不等于
                if (item.conditions == 4) {
                    if (vals.indexOf('' + subItem.controlValue) == -1) {
                        ar.push(subItem);
                    }
                }
                // 5等于
                if (item.conditions == 5) {
                    if (vals.indexOf('' + subItem.controlValue) != -1) {
                        ar.push(subItem);
                    }
                }
                // 6包含
                if (item.conditions == 6) {
                    if (vals.indexOf('' + subItem.controlValue) != -1) {
                        ar.push(subItem);
                    }
                }
                // 7不包含
                if (item.conditions == 7) {
                    if (vals.indexOf('' + subItem.controlValue) == -1) {
                        ar.push(subItem);
                    }
                }
                // 8提示
                if (item.conditions == 8) {}
                // 9隐藏
                if (item.conditions == 9) {}
            });
            if (array.length == 0) {
                array = ar;
            } else {
                array = T.intersection(array, ar);
            }
        });
        return array;
    },

    getInsureData: function getInsureData() {
        return _insureData;
    },
    getInsureDataItem: function (_getInsureDataItem) {
        function getInsureDataItem(_x) {
            return _getInsureDataItem.apply(this, arguments);
        }

        getInsureDataItem.toString = function () {
            return _getInsureDataItem.toString();
        };

        return getInsureDataItem;
    }(function (obj) {
        return getInsureDataItem(obj);
    }),
    getTrialItemByInsureKey: function getTrialItemByInsureKey(key) {
        switch (key) {
            case 'sex':
                key = 'sex';
                break;
            case 'birthdate':
                key = 'insurantDate';
                break;
            case 'insuranceDate':
                key = 'insurantDateLimit';
                break;
            case 'insuranceEndDate':
                key = 'insurantDateLimit';
                break;
            case 'jobText':
                key = 'jobLevel';
                break;
        }
        return Trial.getTrialItem(key);
    },
    subtractDate: function subtractDate(num, type) {
        //保费计算是否包含生日当天：0是 1否(这也是一个坑)
        var insureIncludeBirthday = _product.insureIncludeBirthday;
        var time = moment(Trial.now());
        //被保人年龄计算方式：1=起保日期 2=投保日期
        if (_product.insuredAgeCalculation == 1 && _ifSelf) {
            time = moment($(".insuranceDate").val());
        }
        time.subtract(num, type);
        if (!insureIncludeBirthday) {
            time.subtract(1, 'd');
        }
        return T.formatDate("yyyy-MM-dd hh:mm:ss", time);
    },
    calculateInsurantDate: function calculateInsurantDate() {
        var insureDate;
        insureDate = _startDate ? _startDate : T.formatDate("yyyy-MM-dd", Trial.now());
        if (!insureDate && _product.insureTime == 1) {
            T.showTips('请先选择起保日期');
            return;
        }
        return Trial.getInsureDate(insureDate, _product);
    },
    getDefaultDateLimit: function getDefaultDateLimit() {
        return {
            minDate: moment(Trial.now()).subtract(120, 'y'),
            maxDate: moment(Trial.now())
        };
    },
    calculateDateLimit: function calculateDateLimit(obj) {
        // 投保人模块
        if (obj.mid == 10) {
            var dateLimit = {};
            // 出生日期
            if (obj.key == 'birthdate') {
                var now = moment(Trial.now());
                // 为本人投保
                if (_ifSelf) {
                    dateLimit = Trial.calculateInsurantDate();
                    if (dateLimit) {
                        dateLimit = Trial.procDateRrestricts(dateLimit, Trial.getInsureModule()[10].attr.birthdate);
                        if (dateLimit.maxDate.isAfter(now)) {
                            dateLimit.maxDate = now;
                            dateLimit.maxDate.subtract(18, 'y');
                        } else {
                            now.subtract(18, 'y');
                            dateLimit.maxDate.subtract(18, 'y');
                            var num = moment([now.year(), dateLimit.maxDate.month(), dateLimit.maxDate.date()]).diff(moment([now.year(), now.month(), now.date()]), 'days');
                            if (num > 0) {
                                dateLimit.maxDate = now;
                            } else {
                                dateLimit.maxDate = now.subtract(-num, 'day');
                                if (dateLimit.minDate.isAfter(dateLimit.maxDate)) {
                                    dateLimit.maxDate = dateLimit.minDate;
                                }
                            }
                        }
                    }
                } else {
                    dateLimit.minDate = moment(Trial.now()).subtract(120, 'y');
                    dateLimit.maxDate = moment(Trial.now()).subtract(18, 'y');
                    if (_insureModule[10]) {
                        console.log('执行约束前时间范围', T.formatDate("yyyy-MM-dd", dateLimit.minDate), T.formatDate("yyyy-MM-dd", dateLimit.maxDate));
                        dateLimit = Trial.procDateRrestricts(dateLimit, Trial.getInsureModule()[10].attr.birthdate);
                    }
                }
                var date = moment(Trial.now()).subtract(120, 'y');
                if (dateLimit.minDate.isBefore(date)) dateLimit.minDate = date;
                if (dateLimit.maxDate.isAfter(moment(Trial.now()))) dateLimit.maxDate = moment(Trial.now());
                return dateLimit;
            } else if (obj.key == 'cardPeriod') {
                var dateLimit = Trial.getDefaultDateLimit();
                dateLimit.maxDate.add(50, 'y');
                return dateLimit;
            } else {
                return Trial.getDefaultDateLimit();
            }
        }
        // 被保险人模块
        else if (obj.mid == 20) {
                if (obj.key == 'cardPeriod') {
                    var dateLimit = Trial.getDefaultDateLimit();
                    dateLimit.maxDate.add(50, 'y');
                    return dateLimit;
                }
                var now = moment(Trial.now());
                var dateLimit = Trial.calculateInsurantDate();

                if (_insureModule[20]) {
                    console.log('执行约束前时间范围', T.formatDate("yyyy-MM-dd", dateLimit.minDate), T.formatDate("yyyy-MM-dd", dateLimit.maxDate));
                    dateLimit = Trial.procDateRrestricts(dateLimit, Trial.getInsureModule()[20].attr['default'].birthdate);
                }

                var date = moment(Trial.now()).subtract(120, 'y');
                if (dateLimit.minDate.isBefore(date)) dateLimit.minDate = date;
                if (dateLimit.maxDate.isAfter(now)) dateLimit.maxDate = now;
                return dateLimit;
            }
            // 受益人模块
            else if (obj.mid == 30) {
                    if (obj.key == 'cardPeriod') {
                        var dateLimit = Trial.getDefaultDateLimit();
                        dateLimit.maxDate.add(50, 'y');
                        return dateLimit;
                    }
                    return Trial.getDefaultDateLimit();
                }
                // 其他模块
                else if (obj.mid == 40) {
                        var insureDate = _startDate ? _startDate : T.formatDate("yyyy-MM-dd", Trial.now()),
                            insureEndDate = _insureData[102] ? _insureData[102][0].insuranceEndDate : T.formatDate("yyyy-MM-dd", Trial.now());
                        if (!insureDate && _product.insureTime == 1) {
                            layer.msg('请先选择起保日期');
                            return;
                        }
                        if (obj.key == 'debtStartTime') {
                            var debtStartTime = moment(insureDate);
                            debtStartTime.subtract(1, 'd');
                            return {
                                minDate: moment(insureDate).subtract(17, 'M'),
                                maxDate: debtStartTime
                            };
                        } else if (obj.key == 'debtEndTime') {
                            var debtEndTime = moment(insureEndDate);
                            debtEndTime.add(1, 'd');
                            return {
                                minDate: debtEndTime,
                                maxDate: debtEndTime
                            };
                        }
                    }
                    // 起保时间
                    else if (obj.mid == 102) {
                            //起保时间为可选，判断投保截止时间
                            var firstDate = _product.firstDate;
                            if (_product.insureTime == 1) {
                                if (_product.firstDate == 0 && !T.isUndefined(_product.deadline) && moment().isAfter(moment(_product.deadline, "HH:mm"))) {
                                    //当天截止
                                    firstDate = firstDate + 1;
                                }
                                if (_product.firstDate >= 0 && !T.isUndefined(_product.nextDayDeadline) && moment().isAfter(moment(_product.nextDayDeadline, "HH:mm"))) {
                                    //次日截止
                                    firstDate = firstDate + 1;
                                }
                                if (obj.key == 'insuranceDate') {
                                    return {
                                        minDate: moment(Trial.now()).add(firstDate, 'd'),
                                        maxDate: moment(Trial.now()).add(_product.latestDate, 'd')
                                    };
                                } else if (obj.key == 'insuranceEndDate') {
                                    var insuranceDate = _startDate ? _startDate : T.formatDate("yyyy-MM-dd", Trial.now());
                                    if (!insuranceDate) return {
                                        minDate: moment(Trial.now()).add(firstDate, 'd'),
                                        maxDate: moment(Trial.now()).add(_product.latestDate, 'd')
                                    };
                                    var insurantDateLimit = Trial.getTrialItem('insurantDateLimit');
                                    var minLimit = 0,
                                        maxLimit = 0;
                                    T.each(insurantDateLimit.dictionaryList, function (item, i) {
                                        if (item.unit == 10) {
                                            if (minLimit == -1 || maxLimit == -1) {
                                                minLimit = item.max;
                                                maxLimit = item.min;
                                                unit = item.unit;
                                            } else if (item.max > minLimit) {
                                                minLimit = item.max;
                                            } else if (item.min > maxLimit) {
                                                maxLimit = item.min;
                                            }
                                        }
                                    });
                                    dateLimit = {
                                        minDate: moment(insuranceDate),
                                        maxDate: moment(insuranceDate).add(minLimit - 1, 'd')
                                    };
                                    if (_product.insureTimePrecision == 2) {
                                        dateLimit.maxDate.add(1, 'd');
                                    }
                                    return dateLimit;
                                }
                            }
                        } else {
                            var dateLimit = Trial.getDefaultDateLimit();
                            dateLimit.maxDate.add(120, 'y');
                            return dateLimit;
                        }
    },

    trialInsuredPrice: function trialInsuredPrice(tobeParams, cb, noLoading) {
        var insureList = T.clone(tobeParams);
        //if (processing) {
        //    console.log('正在处理试算请求');
        //    return;
        //}
        processing = true;
        var bool,
            startDate = _startDate ? _startDate : T.formatDate("yyyy-MM-dd", Trial.now());

        var obj = {
            uid: Trial.getPartnerId(),
            startDate: startDate,
            trialGenes: Trial.getTrialGenes(),
            insuredList: insureList || []
        };

        T.each(obj.insuredList, function (item, i) {
            obj.insuredList[i].uuid = i;
            if (obj.insuredList[i].sex !== undefined) {
                obj.insuredList[i].sex = obj.insuredList[i].sex == 1 ? "男" : "女";
            }
            if (obj.insuredList[i].haveMedical !== undefined) {
                obj.insuredList[i].haveMedical = obj.insuredList[i].haveMedical == 1 ? "有" : "无";
            }
            if (obj.insuredList[i].buyCount !== undefined) {
                var buyCountValue = obj.insuredList[i].buyCount + "";
                buyCountValue = buyCountValue.indexOf("份") > -1 ? buyCountValue : buyCountValue + "份";
                obj.insuredList[i].buyCount = buyCountValue;
            }
        });

        if (obj.insuredList.length != 0) {
            api.trialInsuredPrice({
                showLoading: !noLoading,
                data: obj,
                method: "POST",
                success: function success(result) {
                    result = typeof result == "string" ? JSON.parse(result) : result;

                    procResult(result);
                }
            });
        } else {
            processing = false;
        }

        function procResult(result) {
            processing = false;
            var resultPriceItem = {
                priceList: [],
                totalPrice: 0
            };
            if (!result.success || result.data.trialResultCode != "70000") {
                //试算失败
                cb && cb({
                    success: false,
                    code: result.code,
                    data: result.data,
                    msg: '保障信息变动或不一致,被保险人价格试算失败'
                });
            } else {
                T.each(result.data.insuredResultVoList, function (item, i) {
                    var price = +item.vipPrice;
                    resultPriceItem.priceList.push(price);
                    resultPriceItem.totalPrice += price;
                });
                resultPriceItem.totalPrice = resultPriceItem.totalPrice.toFixed(2);
                cb && cb(null, resultPriceItem);
            }
        }
    },

    getInsurantSelf: function getInsurantSelf() {
        return _ifSelf;
    },
    setInsurantSelf: function setInsurantSelf(val) {
        _ifSelf = val;
    },
    supportAppoint: function supportAppoint() {
        return _supportAppoint;
    },
    supportOther: function supportOther() {
        return _supportOther;
    },
    supportSelf: function supportSelf() {
        return _supportSelf;
    },
    supportMono: function supportMono() {
        return _supportMono;
    },
    setMono: function setMono(val) {
        _supportMono = val;
    },
    supportMore: function supportMore() {
        return _supportMore;
    },
    getBuyCountData: function getBuyCountData() {
        //判断购买分数是否有限制
        var buyCountTrial = Trial.getTrialItem("buyCount");
        if (!T.isEmpty(buyCountTrial)) {
            var defaultValue = buyCountTrial.defaultValue;
            if (Trial.getTrialGenesMap()['buyCount']) defaultValue = Trial.getTrialGenesMap()['buyCount'].value;
            if (defaultValue.indexOf('份') != -1) defaultValue = defaultValue.substr(0, defaultValue.length - 1);
            var dataList = [];
            if (!T.isUndefined(buyCountTrial)) {
                T.each(buyCountTrial.dictionaryList, function (item, index) {
                    if (item.step > 0) {
                        for (var i = item.min; i <= item.max; i += item.step) {
                            dataList.push(i);
                        }
                    }
                });
            }
            return {
                dataList: dataList,
                'default': defaultValue.replace("份", ""),
                unit: Trial.transUnit(buyCountTrial.dictionaryList[0].unit),
                type: buyCountTrial.controlType
            };
        } else {
            return {};
        }
    },
    // 通过开始结束时间 计算具体天数
    parserInsuranceDate: function parserInsuranceDate(startDate, endDate) {
        startDate = moment(startDate);
        endDate = moment(endDate);
        var val;
        var day = endDate.diff(startDate, 'days') + 1;
        var trailLimit = Trial.getTrialItem("insurantDateLimit");
        trailLimit.dictionaryList = trailLimit.dictionaryList || [];
        T.each(trailLimit.dictionaryList, function (item, i) {
            if (item.max >= day && day >= item.min && item.unit == 10) {
                if (item.step == 0) {
                    val = item.value + "天";
                } else {
                    val = day + "天";
                }
            }
        });
        return val;
    },
    // 通过开始时间计算结束时间范围
    formatInsuranceDate: function formatInsuranceDate(startDate) {
        var val;
        var trialLimit = Trial.getTrialItem("insurantDateLimit");
        var defaultValue = trialLimit.defaultValue;
        var dictionaryList = trialLimit.dictionaryList || [];
        dictionaryList[0] = dictionaryList[0] || {};
        var tmpMax = dictionaryList[0].max;
        var tmpMin = dictionaryList[0].min;
        var tmpUnit = dictionaryList[0].unit; //天：10  月：9  年：8
        var tmpType = dictionaryList[0].type;
        var calculateType = _product.calculateType; //保障期限计算方式 0-自然,1-固定(年=365天, 月=30天)
        var oriStartDate = moment(startDate);
        T.each(dictionaryList, function (item, index) {
            if (item.value && item.value.indexOf('-') == -1) {
                if (item.value + Trial.transUnit(item.unit) == defaultValue) {
                    tmpMax = item.max;
                    tmpMin = item.min;
                    tmpUnit = item.unit;
                    tmpType = item.type;
                }
            } else {
                if (item.step) {
                    for (var i = item.min; i <= item.max; i = i + item.step) {
                        if (i + Trial.transUnit(item.unit) == defaultValue) {
                            tmpMax = i;
                            tmpMin = i;
                            tmpUnit = item.unit;
                            tmpType = item.type;
                            return;
                        }
                    }
                } else {
                    if (item.min + '-' + item.max + Trial.transUnit(item.unit) == defaultValue) {
                        tmpMax = item.max;
                        tmpMin = item.max;
                        tmpUnit = item.unit;
                        tmpType = item.type;
                    }
                }
            }
        });

        if (tmpUnit == 10) {
            val = moment(startDate).add(tmpMax - 1, 'days');
        } else if (tmpUnit == 9) {
            if (calculateType) {
                val = moment(startDate).add(29 + (tmpMax - 1) * 30, 'd');
            } else {
                val = moment(startDate).add(tmpMax, 'M').subtract(1, 'd');
            }
        } else if (tmpUnit == 8) {
            if (calculateType) {
                val = moment(startDate).add(364 + (tmpMax - 1) * 365, 'd');
            } else {
                val = moment(startDate).add(tmpMax, 'y').subtract(1, 'd');
            }
        }
        if (val) {
            val = T.formatDate("yyyy-MM-dd", val);
        }
        if (_product.insureTimePrecision == 2) {
            val = moment(val).add(1, 'd').hours(oriStartDate.hours()).subtract(1, 'seconds');
            val = T.formatDate("yyyy-MM-dd hh:mm:ss", val);
        }
        return val;
    },
    setInsureBeneficiaryType: function setInsureBeneficiaryType(val) {
        _insureBeneficiaryType = val;
    },
    getInsureBeneficiaryType: function getInsureBeneficiaryType() {
        return _insureBeneficiaryType;
    },
    getToWhoData: function getToWhoData() {
        var whoData = [];
        if (Trial.supportSelf()) {
            if (Trial.supportOther() || Trial.supportMore() || Trial.supportMono()) {
                whoData = [{ value: "本人", controlValue: 1 }, { value: "他人", controlValue: 2 }];
            } else {
                whoData = [{ value: "本人", controlValue: 1 }];
            }
        } else {
            whoData = [{ value: "他人", controlValue: 2 }];
        }
        return {
            "name": "为谁投保",
            "keyCode": "toWho",
            "type": 0,
            "values": whoData
        };
    },
    getStartDateData: function getStartDateData() {
        var limitDate = Trial.calculateDateLimit({ mid: 102, key: "insuranceDate" }) || {};
        var minDate = limitDate.minDate || new Date(1920, 1, 1);
        var maxDate = limitDate.maxDate || new Date(2100, 1, 1);
        minDate = T.formatDate("yyyy-MM-dd", minDate);
        maxDate = T.formatDate("yyyy-MM-dd", maxDate);
        console.log(minDate, maxDate, "起保日期");
        return {
            "name": "起保日期",
            "keyCode": "insuranceDate",
            "type": 1,
            "start": minDate,
            "end": maxDate,
            "default": minDate
        };
    },
    checkFormParam: function checkFormParam(param) {
        var mItem, item, i, key, regex, value;
        var flag;
        for (var mid in param) {
            mItem = param[mid] || [];
            if (mid == 20 && !mItem.length && !_ifSelf) {
                T.showTips("请添加被保险人");
                return false;
            }

            for (i = 0; i < mItem.length; i++) {
                item = mItem[i];
                for (key in item) {
                    value = item[key];
                    flag = Trial.checkInput(mid, i, key, value, param, true);
                    if (!flag) {
                        return false;
                    }
                }
            }
        }
        return true;
    },
    checkInput: function checkInput(mid, index, key, value, param, isAll) {
        var modules = Trial.getInsureModule();
        var attrObj = modules[mid].attr.default || modules[mid].attr;
        var attr = attrObj[key];
        var cardRegObj = {};
        if (!attr) {
            return true;
        }
        var arrtReg = attr.regex;
        var regex = insureConfig.regMap[key] || arrtReg || "";
        var msg,
            selectedCardId,
            flag = true;

        //非必填直接通过
        if (!value && !attr.required) {
            return true;
        }

        if (!value && value !== 0) {
            if (!isAll) {
                return true;
            }

            T.showTips("请输入" + attr.name);
            return false;
        }
        if (key === "cardNumber") {
            selectedCardId = param["cardTypeName"] || param[mid][index]["cardTypeName"];
            cardRegObj = insureConfig.cardNumRegexJson[selectedCardId] || {};
            regex = cardRegObj.regex;
            if (selectedCardId == 1) {
                //身份证
                flag = T.isIdCard(value);
            }
        }

        if (mid == 10 || mid == 20 || mid == 102) {
            var trialItem = Trial.getTrialItemByInsureKey(key);
            if (key == 'jobText' && T.isEmpty(trialItem)) {
                trialItem = Trial.getTrialItem('insurantJob');
            }

            var hasError = false;

            if (!T.isEmpty(trialItem)) {
                switch (key) {
                    case 'sex':
                        if (!T.isEmpty(value) && (!_ifSelf && mid != 10 || mid == 10 && _ifSelf)) {
                            var bool = true,
                                sex;
                            T.each(trialItem.dictionaryList, function (item, i) {
                                sex = value == 1 ? '男' : '女';
                                if (sex == item.value) {
                                    bool = false;
                                }
                            });
                            if (bool) {
                                hasError = true;
                                msg = '性别不在承保范围内！';
                            }
                        }
                        break;
                    case 'birthdate':
                        if (!T.isEmpty(value)) {
                            if (mid == 10) {
                                if (!moment(value).isBefore(moment(Trial.now()).subtract(18, 'y'))) {
                                    hasError = true;
                                    msg = '投保人必须大于18岁';
                                }
                            }
                            if (!hasError && _ifSelf == true && mid == 10 || !hasError && mid == 20) {
                                var dateLimit = Trial.calculateDateLimit({ mid: mid, key: 'birthdate' }); //Trial.calculateInsurantDate();
                                if (dateLimit) {
                                    if (!moment(value).isBetween(dateLimit.minDate, dateLimit.maxDate, 'day')) {
                                        if (!moment(value).isSame(dateLimit.minDate, 'day') && !moment(value).isSame(dateLimit.maxDate, 'day')) {
                                            hasError = true;
                                            msg = '年龄不在承保范围内！';
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    case 'insuranceEndDate':
                        if (!T.isEmpty(value) && (!_ifSelf || mid != 10)) {
                            bool = false;
                        }
                        break;
                    case 'jobText':
                        var bool = true;
                        var vals = obj.val.split('-');
                        var level = vals[vals.length - 1];
                        //if (obj.val.indexOf('-') != -1 && (!_ifSelf || obj.mid != 10)) {
                        if (obj.val.indexOf('-') != -1) {
                            T.each(trialItem.dictionaryList, function (item, i) {
                                if (level == item.value) {
                                    bool = false;
                                }
                            });
                            if (bool && trialItem.dictionaryList[0]) {
                                var item = trialItem.dictionaryList[0];
                                if (item.value.indexOf('-') != -1) {
                                    var strs = item.value.replace('类', '').split('-');
                                    for (var i = parseInt(strs[0]); i <= strs[1]; i++) {
                                        if (level == i) {
                                            bool = false;
                                        }
                                    }
                                } else if (item.value.indexOf('类') != -1) {
                                    var str = item.value.replace('类', '');
                                    if (level == str) {
                                        bool = false;
                                    }
                                } else if (item.value.indexOf('不限职业') != -1 || item.value.indexOf('详见职业表') != -1 || item.value.indexOf('特定职业') != -1) {
                                    bool = false;
                                }
                            }
                            if (bool) {
                                hasError = true;
                                msg = '职业不在承保范围内！';
                            }
                        }
                        break;
                }
            } else {
                switch (key) {
                    case 'birthdate':
                        if (!T.isEmpty(val)) {
                            if (mid == 10) {
                                if (!moment(val).isBefore(moment(Trial.now()).subtract(18, 'y'))) {
                                    hasError = true;
                                    msg = '投保人必须大于18岁';
                                }
                            }
                        }
                        break;
                }
            }

            if (hasError) {
                T.showTips(msg);
                return false;
            }
        }

        if (regex || !flag) {
            regex = new RegExp(regex);
            if (!regex.test(value) || !flag) {
                msg = cardRegObj.errorMsg || insureConfig.tipMap[key] || attr.errorRemind || "请输入合法的" + attr.name;
                T.showTips(msg);
                return false;
            }
        }
        return true;
    },
    reset: function reset() {
        opt = {};
        _trialAttr = {};
        _insureSort = [];
        _resultData = {};
        _lastTrialItem = '';
    },
    setReady: function setReady(cb) {
        opt.ready = cb;
    },
    setOnChange: function setOnChange(cb) {
        opt.onChange = cb;
    }
};

module.exports = Trial; 
 			}); 		define("utils/underscore.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

//     Underscore.js 1.8.3
//     http://underscorejs.org
//     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.

(function () {

  // Baseline setup
  // --------------

  // Establish the root object, `window` in the browser, or `exports` on the server.
  var root = this || {};

  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;

  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype,
      ObjProto = Object.prototype,
      FuncProto = Function.prototype;

  // Create quick reference variables for speed access to core prototypes.
  var push = ArrayProto.push,
      slice = ArrayProto.slice,
      toString = ObjProto.toString,
      hasOwnProperty = ObjProto.hasOwnProperty;

  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var nativeIsArray = Array.isArray,
      nativeKeys = Object.keys,
      nativeBind = FuncProto.bind,
      nativeCreate = Object.create;

  // Naked function reference for surrogate-prototype-swapping.
  var Ctor = function Ctor() {};

  // Create a safe reference to the Underscore object for use below.
  var _ = function _(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

  // Export the Underscore object for **Node.js**, with
  // backwards-compatibility for the old `require()` API. If we're in
  // the browser, add `_` as a global object.
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }

  // Current version.
  _.VERSION = '1.8.3';

  // Internal function that returns an efficient (for current engines) version
  // of the passed-in callback, to be repeatedly applied in other Underscore
  // functions.
  var optimizeCb = function optimizeCb(func, context, argCount) {
    if (context === void 0) return func;
    switch (argCount == null ? 3 : argCount) {
      case 1:
        return function (value) {
          return func.call(context, value);
        };
      case 2:
        return function (value, other) {
          return func.call(context, value, other);
        };
      case 3:
        return function (value, index, collection) {
          return func.call(context, value, index, collection);
        };
      case 4:
        return function (accumulator, value, index, collection) {
          return func.call(context, accumulator, value, index, collection);
        };
    }
    return function () {
      return func.apply(context, arguments);
    };
  };

  // A mostly-internal function to generate callbacks that can be applied
  // to each element in a collection, returning the desired result — either
  // identity, an arbitrary callback, a property matcher, or a property accessor.
  var cb = function cb(value, context, argCount) {
    if (value == null) return _.identity;
    if (_.isFunction(value)) return optimizeCb(value, context, argCount);
    if (_.isObject(value)) return _.matcher(value);
    return _.property(value);
  };
  _.iteratee = function (value, context) {
    return cb(value, context, Infinity);
  };

  // An internal function for creating assigner functions.
  var createAssigner = function createAssigner(keysFunc, undefinedOnly) {
    return function (obj) {
      var length = arguments.length;
      if (length < 2 || obj == null) return obj;
      for (var index = 1; index < length; index++) {
        var source = arguments[index],
            keys = keysFunc(source),
            l = keys.length;
        for (var i = 0; i < l; i++) {
          var key = keys[i];
          if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
        }
      }
      return obj;
    };
  };

  // An internal function for creating a new object that inherits from another.
  var baseCreate = function baseCreate(prototype) {
    if (!_.isObject(prototype)) return {};
    if (nativeCreate) return nativeCreate(prototype);
    Ctor.prototype = prototype;
    var result = new Ctor();
    Ctor.prototype = null;
    return result;
  };

  var property = function property(key) {
    return function (obj) {
      return obj == null ? void 0 : obj[key];
    };
  };

  // Helper for collection methods to determine whether a collection
  // should be iterated as an array or as an object
  // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
  // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
  var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
  var getLength = property('length');
  var isArrayLike = function isArrayLike(collection) {
    var length = getLength(collection);
    return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
  };

  // Collection Functions
  // --------------------

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles raw objects in addition to array-likes. Treats all
  // sparse array-likes as if they were dense.
  _.each = _.forEach = function (obj, iteratee, context) {
    iteratee = optimizeCb(iteratee, context);
    var i, length;
    if (isArrayLike(obj)) {
      for (i = 0, length = obj.length; i < length; i++) {
        iteratee(obj[i], i, obj);
      }
    } else {
      var keys = _.keys(obj);
      for (i = 0, length = keys.length; i < length; i++) {
        iteratee(obj[keys[i]], keys[i], obj);
      }
    }
    return obj;
  };

  // Return the results of applying the iteratee to each element.
  _.map = _.collect = function (obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    var keys = !isArrayLike(obj) && _.keys(obj),
        length = (keys || obj).length,
        results = Array(length);
    for (var index = 0; index < length; index++) {
      var currentKey = keys ? keys[index] : index;
      results[index] = iteratee(obj[currentKey], currentKey, obj);
    }
    return results;
  };

  // Create a reducing function iterating left or right.
  function createReduce(dir) {
    // Optimized iterator function as using arguments.length
    // in the main function will deoptimize the, see #1991.
    function iterator(obj, iteratee, memo, keys, index, length) {
      for (; index >= 0 && index < length; index += dir) {
        var currentKey = keys ? keys[index] : index;
        memo = iteratee(memo, obj[currentKey], currentKey, obj);
      }
      return memo;
    }

    return function (obj, iteratee, memo, context) {
      iteratee = optimizeCb(iteratee, context, 4);
      var keys = !isArrayLike(obj) && _.keys(obj),
          length = (keys || obj).length,
          index = dir > 0 ? 0 : length - 1;
      // Determine the initial value if none is provided.
      if (arguments.length < 3) {
        memo = obj[keys ? keys[index] : index];
        index += dir;
      }
      return iterator(obj, iteratee, memo, keys, index, length);
    };
  }

  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`.
  _.reduce = _.foldl = _.inject = createReduce(1);

  // The right-associative version of reduce, also known as `foldr`.
  _.reduceRight = _.foldr = createReduce(-1);

  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function (obj, predicate, context) {
    var key;
    if (isArrayLike(obj)) {
      key = _.findIndex(obj, predicate, context);
    } else {
      key = _.findKey(obj, predicate, context);
    }
    if (key !== void 0 && key !== -1) return obj[key];
  };

  // Return all the elements that pass a truth test.
  // Aliased as `select`.
  _.filter = _.select = function (obj, predicate, context) {
    var results = [];
    predicate = cb(predicate, context);
    _.each(obj, function (value, index, list) {
      if (predicate(value, index, list)) results.push(value);
    });
    return results;
  };

  // Return all the elements for which a truth test fails.
  _.reject = function (obj, predicate, context) {
    return _.filter(obj, _.negate(cb(predicate)), context);
  };

  // Determine whether all of the elements match a truth test.
  // Aliased as `all`.
  _.every = _.all = function (obj, predicate, context) {
    predicate = cb(predicate, context);
    var keys = !isArrayLike(obj) && _.keys(obj),
        length = (keys || obj).length;
    for (var index = 0; index < length; index++) {
      var currentKey = keys ? keys[index] : index;
      if (!predicate(obj[currentKey], currentKey, obj)) return false;
    }
    return true;
  };

  // Determine if at least one element in the object matches a truth test.
  // Aliased as `any`.
  _.some = _.any = function (obj, predicate, context) {
    predicate = cb(predicate, context);
    var keys = !isArrayLike(obj) && _.keys(obj),
        length = (keys || obj).length;
    for (var index = 0; index < length; index++) {
      var currentKey = keys ? keys[index] : index;
      if (predicate(obj[currentKey], currentKey, obj)) return true;
    }
    return false;
  };

  // Determine if the array or object contains a given item (using `===`).
  // Aliased as `includes` and `include`.
  _.contains = _.includes = _.include = function (obj, item, fromIndex, guard) {
    if (!isArrayLike(obj)) obj = _.values(obj);
    if (typeof fromIndex != 'number' || guard) fromIndex = 0;
    return _.indexOf(obj, item, fromIndex) >= 0;
  };

  // Invoke a method (with arguments) on every item in a collection.
  _.invoke = function (obj, method) {
    var args = slice.call(arguments, 2);
    var isFunc = _.isFunction(method);
    return _.map(obj, function (value) {
      var func = isFunc ? method : value[method];
      return func == null ? func : func.apply(value, args);
    });
  };

  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function (obj, key) {
    return _.map(obj, _.property(key));
  };

  // Convenience version of a common use case of `filter`: selecting only objects
  // containing specific `key:value` pairs.
  _.where = function (obj, attrs) {
    return _.filter(obj, _.matcher(attrs));
  };

  // Convenience version of a common use case of `find`: getting the first object
  // containing specific `key:value` pairs.
  _.findWhere = function (obj, attrs) {
    return _.find(obj, _.matcher(attrs));
  };

  // Return the maximum element (or element-based computation).
  _.max = function (obj, iteratee, context) {
    var result = -Infinity,
        lastComputed = -Infinity,
        value,
        computed;
    if (iteratee == null && obj != null) {
      obj = isArrayLike(obj) ? obj : _.values(obj);
      for (var i = 0, length = obj.length; i < length; i++) {
        value = obj[i];
        if (value > result) {
          result = value;
        }
      }
    } else {
      iteratee = cb(iteratee, context);
      _.each(obj, function (value, index, list) {
        computed = iteratee(value, index, list);
        if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
          result = value;
          lastComputed = computed;
        }
      });
    }
    return result;
  };

  // Return the minimum element (or element-based computation).
  _.min = function (obj, iteratee, context) {
    var result = Infinity,
        lastComputed = Infinity,
        value,
        computed;
    if (iteratee == null && obj != null) {
      obj = isArrayLike(obj) ? obj : _.values(obj);
      for (var i = 0, length = obj.length; i < length; i++) {
        value = obj[i];
        if (value < result) {
          result = value;
        }
      }
    } else {
      iteratee = cb(iteratee, context);
      _.each(obj, function (value, index, list) {
        computed = iteratee(value, index, list);
        if (computed < lastComputed || computed === Infinity && result === Infinity) {
          result = value;
          lastComputed = computed;
        }
      });
    }
    return result;
  };

  // Shuffle a collection, using the modern version of the
  // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  _.shuffle = function (obj) {
    var set = isArrayLike(obj) ? obj : _.values(obj);
    var length = set.length;
    var shuffled = Array(length);
    for (var index = 0, rand; index < length; index++) {
      rand = _.random(0, index);
      if (rand !== index) shuffled[index] = shuffled[rand];
      shuffled[rand] = set[index];
    }
    return shuffled;
  };

  // Sample **n** random values from a collection.
  // If **n** is not specified, returns a single random element.
  // The internal `guard` argument allows it to work with `map`.
  _.sample = function (obj, n, guard) {
    if (n == null || guard) {
      if (!isArrayLike(obj)) obj = _.values(obj);
      return obj[_.random(obj.length - 1)];
    }
    return _.shuffle(obj).slice(0, Math.max(0, n));
  };

  // Sort the object's values by a criterion produced by an iteratee.
  _.sortBy = function (obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    return _.pluck(_.map(obj, function (value, index, list) {
      return {
        value: value,
        index: index,
        criteria: iteratee(value, index, list)
      };
    }).sort(function (left, right) {
      var a = left.criteria;
      var b = right.criteria;
      if (a !== b) {
        if (a > b || a === void 0) return 1;
        if (a < b || b === void 0) return -1;
      }
      return left.index - right.index;
    }), 'value');
  };

  // An internal function used for aggregate "group by" operations.
  var group = function group(behavior) {
    return function (obj, iteratee, context) {
      var result = {};
      iteratee = cb(iteratee, context);
      _.each(obj, function (value, index) {
        var key = iteratee(value, index, obj);
        behavior(result, value, key);
      });
      return result;
    };
  };

  // Groups the object's values by a criterion. Pass either a string attribute
  // to group by, or a function that returns the criterion.
  _.groupBy = group(function (result, value, key) {
    if (_.has(result, key)) result[key].push(value);else result[key] = [value];
  });

  // Indexes the object's values by a criterion, similar to `groupBy`, but for
  // when you know that your index values will be unique.
  _.indexBy = group(function (result, value, key) {
    result[key] = value;
  });

  // Counts instances of an object that group by a certain criterion. Pass
  // either a string attribute to count by, or a function that returns the
  // criterion.
  _.countBy = group(function (result, value, key) {
    if (_.has(result, key)) result[key]++;else result[key] = 1;
  });

  // Safely create a real, live array from anything iterable.
  _.toArray = function (obj) {
    if (!obj) return [];
    if (_.isArray(obj)) return slice.call(obj);
    if (isArrayLike(obj)) return _.map(obj, _.identity);
    return _.values(obj);
  };

  // Return the number of elements in an object.
  _.size = function (obj) {
    if (obj == null) return 0;
    return isArrayLike(obj) ? obj.length : _.keys(obj).length;
  };

  // Split a collection into two arrays: one whose elements all satisfy the given
  // predicate, and one whose elements all do not satisfy the predicate.
  _.partition = function (obj, predicate, context) {
    predicate = cb(predicate, context);
    var pass = [],
        fail = [];
    _.each(obj, function (value, key, obj) {
      (predicate(value, key, obj) ? pass : fail).push(value);
    });
    return [pass, fail];
  };

  // Array Functions
  // ---------------

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head` and `take`. The **guard** check
  // allows it to work with `_.map`.
  _.first = _.head = _.take = function (array, n, guard) {
    if (array == null) return void 0;
    if (n == null || guard) return array[0];
    return _.initial(array, array.length - n);
  };

  // Returns everything but the last entry of the array. Especially useful on
  // the arguments object. Passing **n** will return all the values in
  // the array, excluding the last N.
  _.initial = function (array, n, guard) {
    return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
  };

  // Get the last element of an array. Passing **n** will return the last N
  // values in the array.
  _.last = function (array, n, guard) {
    if (array == null) return void 0;
    if (n == null || guard) return array[array.length - 1];
    return _.rest(array, Math.max(0, array.length - n));
  };

  // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  // Especially useful on the arguments object. Passing an **n** will return
  // the rest N values in the array.
  _.rest = _.tail = _.drop = function (array, n, guard) {
    return slice.call(array, n == null || guard ? 1 : n);
  };

  // Trim out all falsy values from an array.
  _.compact = function (array) {
    return _.filter(array, _.identity);
  };

  // Internal implementation of a recursive `flatten` function.
  var flatten = function flatten(input, shallow, strict, startIndex) {
    var output = [],
        idx = 0;
    for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
      var value = input[i];
      if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
        //flatten current level of array or arguments object
        if (!shallow) value = flatten(value, shallow, strict);
        var j = 0,
            len = value.length;
        output.length += len;
        while (j < len) {
          output[idx++] = value[j++];
        }
      } else if (!strict) {
        output[idx++] = value;
      }
    }
    return output;
  };

  // Flatten out an array, either recursively (by default), or just one level.
  _.flatten = function (array, shallow) {
    return flatten(array, shallow, false);
  };

  // Return a version of the array that does not contain the specified value(s).
  _.without = function (array) {
    return _.difference(array, slice.call(arguments, 1));
  };

  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // Aliased as `unique`.
  _.uniq = _.unique = function (array, isSorted, iteratee, context) {
    if (!_.isBoolean(isSorted)) {
      context = iteratee;
      iteratee = isSorted;
      isSorted = false;
    }
    if (iteratee != null) iteratee = cb(iteratee, context);
    var result = [];
    var seen = [];
    for (var i = 0, length = getLength(array); i < length; i++) {
      var value = array[i],
          computed = iteratee ? iteratee(value, i, array) : value;
      if (isSorted) {
        if (!i || seen !== computed) result.push(value);
        seen = computed;
      } else if (iteratee) {
        if (!_.contains(seen, computed)) {
          seen.push(computed);
          result.push(value);
        }
      } else if (!_.contains(result, value)) {
        result.push(value);
      }
    }
    return result;
  };

  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function () {
    return _.uniq(flatten(arguments, true, true));
  };

  // Produce an array that contains every item shared between all the
  // passed-in arrays.
  _.intersection = function (array) {
    var result = [];
    var argsLength = arguments.length;
    for (var i = 0, length = getLength(array); i < length; i++) {
      var item = array[i];
      if (_.contains(result, item)) continue;
      for (var j = 1; j < argsLength; j++) {
        if (!_.contains(arguments[j], item)) break;
      }
      if (j === argsLength) result.push(item);
    }
    return result;
  };

  // Take the difference between one array and a number of other arrays.
  // Only the elements present in just the first array will remain.
  _.difference = function (array) {
    var rest = flatten(arguments, true, true, 1);
    return _.filter(array, function (value) {
      return !_.contains(rest, value);
    });
  };

  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  _.zip = function () {
    return _.unzip(arguments);
  };

  // Complement of _.zip. Unzip accepts an array of arrays and groups
  // each array's elements on shared indices
  _.unzip = function (array) {
    var length = array && _.max(array, getLength).length || 0;
    var result = Array(length);

    for (var index = 0; index < length; index++) {
      result[index] = _.pluck(array, index);
    }
    return result;
  };

  // Converts lists into objects. Pass either a single array of `[key, value]`
  // pairs, or two parallel arrays of the same length -- one of keys, and one of
  // the corresponding values.
  _.object = function (list, values) {
    var result = {};
    for (var i = 0, length = getLength(list); i < length; i++) {
      if (values) {
        result[list[i]] = values[i];
      } else {
        result[list[i][0]] = list[i][1];
      }
    }
    return result;
  };

  // Generator function to create the findIndex and findLastIndex functions
  function createPredicateIndexFinder(dir) {
    return function (array, predicate, context) {
      predicate = cb(predicate, context);
      var length = getLength(array);
      var index = dir > 0 ? 0 : length - 1;
      for (; index >= 0 && index < length; index += dir) {
        if (predicate(array[index], index, array)) return index;
      }
      return -1;
    };
  }

  // Returns the first index on an array-like that passes a predicate test
  _.findIndex = createPredicateIndexFinder(1);
  _.findLastIndex = createPredicateIndexFinder(-1);

  // Use a comparator function to figure out the smallest index at which
  // an object should be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = function (array, obj, iteratee, context) {
    iteratee = cb(iteratee, context, 1);
    var value = iteratee(obj);
    var low = 0,
        high = getLength(array);
    while (low < high) {
      var mid = Math.floor((low + high) / 2);
      if (iteratee(array[mid]) < value) low = mid + 1;else high = mid;
    }
    return low;
  };

  // Generator function to create the indexOf and lastIndexOf functions
  function createIndexFinder(dir, predicateFind, sortedIndex) {
    return function (array, item, idx) {
      var i = 0,
          length = getLength(array);
      if (typeof idx == 'number') {
        if (dir > 0) {
          i = idx >= 0 ? idx : Math.max(idx + length, i);
        } else {
          length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
        }
      } else if (sortedIndex && idx && length) {
        idx = sortedIndex(array, item);
        return array[idx] === item ? idx : -1;
      }
      if (item !== item) {
        idx = predicateFind(slice.call(array, i, length), _.isNaN);
        return idx >= 0 ? idx + i : -1;
      }
      for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
        if (array[idx] === item) return idx;
      }
      return -1;
    };
  }

  // Return the position of the first occurrence of an item in an array,
  // or -1 if the item is not included in the array.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
  _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);

  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function (start, stop, step) {
    if (stop == null) {
      stop = start || 0;
      start = 0;
    }
    step = step || 1;

    var length = Math.max(Math.ceil((stop - start) / step), 0);
    var range = Array(length);

    for (var idx = 0; idx < length; idx++, start += step) {
      range[idx] = start;
    }

    return range;
  };

  // Function (ahem) Functions
  // ------------------

  // Determines whether to execute a function as a constructor
  // or a normal function with the provided arguments
  var executeBound = function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
    if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
    var self = baseCreate(sourceFunc.prototype);
    var result = sourceFunc.apply(self, args);
    if (_.isObject(result)) return result;
    return self;
  };

  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  // available.
  _.bind = function (func, context) {
    if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
    var args = slice.call(arguments, 2);
    var bound = function bound() {
      return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
    };
    return bound;
  };

  // Partially apply a function by creating a version that has had some of its
  // arguments pre-filled, without changing its dynamic `this` context. _ acts
  // as a placeholder, allowing any combination of arguments to be pre-filled.
  _.partial = function (func) {
    var boundArgs = slice.call(arguments, 1);
    var bound = function bound() {
      var position = 0,
          length = boundArgs.length;
      var args = Array(length);
      for (var i = 0; i < length; i++) {
        args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
      }
      while (position < arguments.length) {
        args.push(arguments[position++]);
      }return executeBound(func, bound, this, this, args);
    };
    return bound;
  };

  // Bind a number of an object's methods to that object. Remaining arguments
  // are the method names to be bound. Useful for ensuring that all callbacks
  // defined on an object belong to it.
  _.bindAll = function (obj) {
    var i,
        length = arguments.length,
        key;
    if (length <= 1) throw new Error('bindAll must be passed function names');
    for (i = 1; i < length; i++) {
      key = arguments[i];
      obj[key] = _.bind(obj[key], obj);
    }
    return obj;
  };

  // Memoize an expensive function by storing its results.
  _.memoize = function (func, hasher) {
    var memoize = function memoize(key) {
      var cache = memoize.cache;
      var address = '' + (hasher ? hasher.apply(this, arguments) : key);
      if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
      return cache[address];
    };
    memoize.cache = {};
    return memoize;
  };

  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  _.delay = function (func, wait) {
    var args = slice.call(arguments, 2);
    return setTimeout(function () {
      return func.apply(null, args);
    }, wait);
  };

  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  _.defer = _.partial(_.delay, _, 1);

  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time. Normally, the throttled function will run
  // as much as it can, without ever going more than once per `wait` duration;
  // but if you'd like to disable the execution on the leading edge, pass
  // `{leading: false}`. To disable execution on the trailing edge, ditto.
  _.throttle = function (func, wait, options) {
    var context, args, result;
    var timeout = null;
    var previous = 0;
    if (!options) options = {};
    var later = function later() {
      previous = options.leading === false ? 0 : _.now();
      timeout = null;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    };
    return function () {
      var now = _.now();
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0 || remaining > wait) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        previous = now;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };
  };

  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds. If `immediate` is passed, trigger the function on the
  // leading edge, instead of the trailing.
  _.debounce = function (func, wait, immediate) {
    var timeout, args, context, timestamp, result;

    var later = function later() {
      var last = _.now() - timestamp;

      if (last < wait && last >= 0) {
        timeout = setTimeout(later, wait - last);
      } else {
        timeout = null;
        if (!immediate) {
          result = func.apply(context, args);
          if (!timeout) context = args = null;
        }
      }
    };

    return function () {
      context = this;
      args = arguments;
      timestamp = _.now();
      var callNow = immediate && !timeout;
      if (!timeout) timeout = setTimeout(later, wait);
      if (callNow) {
        result = func.apply(context, args);
        context = args = null;
      }

      return result;
    };
  };

  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  _.wrap = function (func, wrapper) {
    return _.partial(wrapper, func);
  };

  // Returns a negated version of the passed-in predicate.
  _.negate = function (predicate) {
    return function () {
      return !predicate.apply(this, arguments);
    };
  };

  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  _.compose = function () {
    var args = arguments;
    var start = args.length - 1;
    return function () {
      var i = start;
      var result = args[start].apply(this, arguments);
      while (i--) {
        result = args[i].call(this, result);
      }return result;
    };
  };

  // Returns a function that will only be executed on and after the Nth call.
  _.after = function (times, func) {
    return function () {
      if (--times < 1) {
        return func.apply(this, arguments);
      }
    };
  };

  // Returns a function that will only be executed up to (but not including) the Nth call.
  _.before = function (times, func) {
    var memo;
    return function () {
      if (--times > 0) {
        memo = func.apply(this, arguments);
      }
      if (times <= 1) func = null;
      return memo;
    };
  };

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = _.partial(_.before, 2);

  // Object Functions
  // ----------------

  // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
  var hasEnumBug = !{ toString: null }.propertyIsEnumerable('toString');
  var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

  function collectNonEnumProps(obj, keys) {
    var nonEnumIdx = nonEnumerableProps.length;
    var constructor = obj.constructor;
    var proto = _.isFunction(constructor) && constructor.prototype || ObjProto;

    // Constructor is a special case.
    var prop = 'constructor';
    if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);

    while (nonEnumIdx--) {
      prop = nonEnumerableProps[nonEnumIdx];
      if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
        keys.push(prop);
      }
    }
  }

  // Retrieve the names of an object's own properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = function (obj) {
    if (!_.isObject(obj)) return [];
    if (nativeKeys) return nativeKeys(obj);
    var keys = [];
    for (var key in obj) {
      if (_.has(obj, key)) keys.push(key);
    } // Ahem, IE < 9.
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
  };

  // Retrieve all the property names of an object.
  _.allKeys = function (obj) {
    if (!_.isObject(obj)) return [];
    var keys = [];
    for (var key in obj) {
      keys.push(key);
    } // Ahem, IE < 9.
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
  };

  // Retrieve the values of an object's properties.
  _.values = function (obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var values = Array(length);
    for (var i = 0; i < length; i++) {
      values[i] = obj[keys[i]];
    }
    return values;
  };

  // Returns the results of applying the iteratee to each element of the object
  // In contrast to _.map it returns an object
  _.mapObject = function (obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    var keys = _.keys(obj),
        length = keys.length,
        results = {},
        currentKey;
    for (var index = 0; index < length; index++) {
      currentKey = keys[index];
      results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
    }
    return results;
  };

  // Convert an object into a list of `[key, value]` pairs.
  _.pairs = function (obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var pairs = Array(length);
    for (var i = 0; i < length; i++) {
      pairs[i] = [keys[i], obj[keys[i]]];
    }
    return pairs;
  };

  // Invert the keys and values of an object. The values must be serializable.
  _.invert = function (obj) {
    var result = {};
    var keys = _.keys(obj);
    for (var i = 0, length = keys.length; i < length; i++) {
      result[obj[keys[i]]] = keys[i];
    }
    return result;
  };

  // Return a sorted list of the function names available on the object.
  // Aliased as `methods`
  _.functions = _.methods = function (obj) {
    var names = [];
    for (var key in obj) {
      if (_.isFunction(obj[key])) names.push(key);
    }
    return names.sort();
  };

  // Extend a given object with all the properties in passed-in object(s).
  _.extend = createAssigner(_.allKeys);

  // Assigns a given object with all the own properties in the passed-in object(s)
  // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
  _.extendOwn = _.assign = createAssigner(_.keys);

  // Returns the first key on an object that passes a predicate test
  _.findKey = function (obj, predicate, context) {
    predicate = cb(predicate, context);
    var keys = _.keys(obj),
        key;
    for (var i = 0, length = keys.length; i < length; i++) {
      key = keys[i];
      if (predicate(obj[key], key, obj)) return key;
    }
  };

  // Return a copy of the object only containing the whitelisted properties.
  _.pick = function (object, oiteratee, context) {
    var result = {},
        obj = object,
        iteratee,
        keys;
    if (obj == null) return result;
    if (_.isFunction(oiteratee)) {
      keys = _.allKeys(obj);
      iteratee = optimizeCb(oiteratee, context);
    } else {
      keys = flatten(arguments, false, false, 1);
      iteratee = function iteratee(value, key, obj) {
        return key in obj;
      };
      obj = Object(obj);
    }
    for (var i = 0, length = keys.length; i < length; i++) {
      var key = keys[i];
      var value = obj[key];
      if (iteratee(value, key, obj)) result[key] = value;
    }
    return result;
  };

  // Return a copy of the object without the blacklisted properties.
  _.omit = function (obj, iteratee, context) {
    if (_.isFunction(iteratee)) {
      iteratee = _.negate(iteratee);
    } else {
      var keys = _.map(flatten(arguments, false, false, 1), String);
      iteratee = function iteratee(value, key) {
        return !_.contains(keys, key);
      };
    }
    return _.pick(obj, iteratee, context);
  };

  // Fill in a given object with default properties.
  _.defaults = createAssigner(_.allKeys, true);

  // Creates an object that inherits from the given prototype object.
  // If additional properties are provided then they will be added to the
  // created object.
  _.create = function (prototype, props) {
    var result = baseCreate(prototype);
    if (props) _.extendOwn(result, props);
    return result;
  };

  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function (obj) {
    if (!_.isObject(obj)) return obj;
    return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };

  // Invokes interceptor with the obj, and then returns obj.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  _.tap = function (obj, interceptor) {
    interceptor(obj);
    return obj;
  };

  // Returns whether an object has a given set of `key:value` pairs.
  _.isMatch = function (object, attrs) {
    var keys = _.keys(attrs),
        length = keys.length;
    if (object == null) return !length;
    var obj = Object(object);
    for (var i = 0; i < length; i++) {
      var key = keys[i];
      if (attrs[key] !== obj[key] || !(key in obj)) return false;
    }
    return true;
  };

  // Internal recursive comparison function for `isEqual`.
  var eq = function eq(a, b, aStack, bStack) {
    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
    if (a === b) return a !== 0 || 1 / a === 1 / b;
    // A strict comparison is necessary because `null == undefined`.
    if (a == null || b == null) return a === b;
    // Unwrap any wrapped objects.
    if (a instanceof _) a = a._wrapped;
    if (b instanceof _) b = b._wrapped;
    // Compare `[[Class]]` names.
    var className = toString.call(a);
    if (className !== toString.call(b)) return false;
    switch (className) {
      // Strings, numbers, regular expressions, dates, and booleans are compared by value.
      case '[object RegExp]':
      // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
      case '[object String]':
        // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
        // equivalent to `new String("5")`.
        return '' + a === '' + b;
      case '[object Number]':
        // `NaN`s are equivalent, but non-reflexive.
        // Object(NaN) is equivalent to NaN
        if (+a !== +a) return +b !== +b;
        // An `egal` comparison is performed for other numeric values.
        return +a === 0 ? 1 / +a === 1 / b : +a === +b;
      case '[object Date]':
      case '[object Boolean]':
        // Coerce dates and booleans to numeric primitive values. Dates are compared by their
        // millisecond representations. Note that invalid dates with millisecond representations
        // of `NaN` are not equivalent.
        return +a === +b;
    }

    var areArrays = className === '[object Array]';
    if (!areArrays) {
      if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) != 'object' || (typeof b === 'undefined' ? 'undefined' : _typeof(b)) != 'object') return false;

      // Objects with different constructors are not equivalent, but `Object`s or `Array`s
      // from different frames are.
      var aCtor = a.constructor,
          bCtor = b.constructor;
      if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) && 'constructor' in a && 'constructor' in b) {
        return false;
      }
    }
    // Assume equality for cyclic structures. The algorithm for detecting cyclic
    // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.

    // Initializing stack of traversed objects.
    // It's done here since we only need them for objects and arrays comparison.
    aStack = aStack || [];
    bStack = bStack || [];
    var length = aStack.length;
    while (length--) {
      // Linear search. Performance is inversely proportional to the number of
      // unique nested structures.
      if (aStack[length] === a) return bStack[length] === b;
    }

    // Add the first object to the stack of traversed objects.
    aStack.push(a);
    bStack.push(b);

    // Recursively compare objects and arrays.
    if (areArrays) {
      // Compare array lengths to determine if a deep comparison is necessary.
      length = a.length;
      if (length !== b.length) return false;
      // Deep compare the contents, ignoring non-numeric properties.
      while (length--) {
        if (!eq(a[length], b[length], aStack, bStack)) return false;
      }
    } else {
      // Deep compare objects.
      var keys = _.keys(a),
          key;
      length = keys.length;
      // Ensure that both objects contain the same number of properties before comparing deep equality.
      if (_.keys(b).length !== length) return false;
      while (length--) {
        // Deep compare each member
        key = keys[length];
        if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
      }
    }
    // Remove the first object from the stack of traversed objects.
    aStack.pop();
    bStack.pop();
    return true;
  };

  // Perform a deep comparison to check if two objects are equal.
  _.isEqual = function (a, b) {
    return eq(a, b);
  };

  // Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
  _.isEmpty = function (obj) {
    if (obj == null) return true;
    if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
    return _.keys(obj).length === 0;
  };

  // Is a given value a DOM element?
  _.isElement = function (obj) {
    return !!(obj && obj.nodeType === 1);
  };

  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function (obj) {
    return toString.call(obj) === '[object Array]';
  };

  // Is a given variable an object?
  _.isObject = function (obj) {
    var type = typeof obj === 'undefined' ? 'undefined' : _typeof(obj);
    return type === 'function' || type === 'object' && !!obj;
  };

  // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
  _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function (name) {
    _['is' + name] = function (obj) {
      return toString.call(obj) === '[object ' + name + ']';
    };
  });

  // Define a fallback version of the method in browsers (ahem, IE < 9), where
  // there isn't any inspectable "Arguments" type.
  if (!_.isArguments(arguments)) {
    _.isArguments = function (obj) {
      return _.has(obj, 'callee');
    };
  }

  // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
  // IE 11 (#1621), and in Safari 8 (#1929).
  if (typeof /./ != 'function' && (typeof Int8Array === 'undefined' ? 'undefined' : _typeof(Int8Array)) != 'object') {
    _.isFunction = function (obj) {
      return typeof obj == 'function' || false;
    };
  }

  // Is a given object a finite number?
  _.isFinite = function (obj) {
    return isFinite(obj) && !isNaN(parseFloat(obj));
  };

  // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  _.isNaN = function (obj) {
    return _.isNumber(obj) && obj !== +obj;
  };

  // Is a given value a boolean?
  _.isBoolean = function (obj) {
    return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
  };

  // Is a given value equal to null?
  _.isNull = function (obj) {
    return obj === null;
  };

  // Is a given variable undefined?
  _.isUndefined = function (obj) {
    return obj === void 0;
  };

  // Shortcut function for checking if an object has a given property directly
  // on itself (in other words, not on a prototype).
  _.has = function (obj, key) {
    return obj != null && hasOwnProperty.call(obj, key);
  };

  // Utility Functions
  // -----------------

  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function () {
    root._ = previousUnderscore;
    return this;
  };

  // Keep the identity function around for default iteratees.
  _.identity = function (value) {
    return value;
  };

  // Predicate-generating functions. Often useful outside of Underscore.
  _.constant = function (value) {
    return function () {
      return value;
    };
  };

  _.noop = function () {};

  _.property = property;

  // Generates a function for a given object that returns a given property.
  _.propertyOf = function (obj) {
    return obj == null ? function () {} : function (key) {
      return obj[key];
    };
  };

  // Returns a predicate for checking whether an object has a given set of
  // `key:value` pairs.
  _.matcher = _.matches = function (attrs) {
    attrs = _.extendOwn({}, attrs);
    return function (obj) {
      return _.isMatch(obj, attrs);
    };
  };

  // Run a function **n** times.
  _.times = function (n, iteratee, context) {
    var accum = Array(Math.max(0, n));
    iteratee = optimizeCb(iteratee, context, 1);
    for (var i = 0; i < n; i++) {
      accum[i] = iteratee(i);
    }return accum;
  };

  // Return a random integer between min and max (inclusive).
  _.random = function (min, max) {
    if (max == null) {
      max = min;
      min = 0;
    }
    return min + Math.floor(Math.random() * (max - min + 1));
  };

  // A (possibly faster) way to get the current timestamp as an integer.
  _.now = Date.now || function () {
    return new Date().getTime();
  };

  // List of HTML entities for escaping.
  var escapeMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#x27;',
    '`': '&#x60;'
  };
  var unescapeMap = _.invert(escapeMap);

  // Functions for escaping and unescaping strings to/from HTML interpolation.
  var createEscaper = function createEscaper(map) {
    var escaper = function escaper(match) {
      return map[match];
    };
    // Regexes for identifying a key that needs to be escaped
    var source = '(?:' + _.keys(map).join('|') + ')';
    var testRegexp = RegExp(source);
    var replaceRegexp = RegExp(source, 'g');
    return function (string) {
      string = string == null ? '' : '' + string;
      return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
    };
  };
  _.escape = createEscaper(escapeMap);
  _.unescape = createEscaper(unescapeMap);

  // If the value of the named `property` is a function then invoke it with the
  // `object` as context; otherwise, return it.
  _.result = function (object, property, fallback) {
    var value = object == null ? void 0 : object[property];
    if (value === void 0) {
      value = fallback;
    }
    return _.isFunction(value) ? value.call(object) : value;
  };

  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function (prefix) {
    var id = ++idCounter + '';
    return prefix ? prefix + id : id;
  };

  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
    evaluate: /<%([\s\S]+?)%>/g,
    interpolate: /<%=([\s\S]+?)%>/g,
    escape: /<%-([\s\S]+?)%>/g
  };

  // When customizing `templateSettings`, if you don't want to define an
  // interpolation, evaluation or escaping regex, we need one that is
  // guaranteed not to match.
  var noMatch = /(.)^/;

  // Certain characters need to be escaped so that they can be put into a
  // string literal.
  var escapes = {
    "'": "'",
    '\\': '\\',
    '\r': 'r',
    '\n': 'n',
    '\u2028': 'u2028',
    '\u2029': 'u2029'
  };

  var escaper = /\\|'|\r|\n|\u2028|\u2029/g;

  var escapeChar = function escapeChar(match) {
    return '\\' + escapes[match];
  };

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  // NB: `oldSettings` only exists for backwards compatibility.
  _.template = function (text, settings, oldSettings) {
    if (!settings && oldSettings) settings = oldSettings;
    settings = _.defaults({}, settings, _.templateSettings);

    // Combine delimiters into one regular expression via alternation.
    var matcher = RegExp([(settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source].join('|') + '|$', 'g');

    // Compile the template source, escaping string literals appropriately.
    var index = 0;
    var source = "__p+='";
    text.replace(matcher, function (match, escape, interpolate, evaluate, offset) {
      source += text.slice(index, offset).replace(escaper, escapeChar);
      index = offset + match.length;

      if (escape) {
        source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
      } else if (interpolate) {
        source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
      } else if (evaluate) {
        source += "';\n" + evaluate + "\n__p+='";
      }

      // Adobe VMs need the match returned to produce the correct offest.
      return match;
    });
    source += "';\n";

    // If a variable is not specified, place data values in local scope.
    if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

    source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n';

    try {
      var render = new Function(settings.variable || 'obj', '_', source);
    } catch (e) {
      e.source = source;
      throw e;
    }

    var template = function template(data) {
      return render.call(this, data, _);
    };

    // Provide the compiled source as a convenience for precompilation.
    var argument = settings.variable || 'obj';
    template.source = 'function(' + argument + '){\n' + source + '}';

    return template;
  };

  // Add a "chain" function. Start chaining a wrapped Underscore object.
  _.chain = function (obj) {
    var instance = _(obj);
    instance._chain = true;
    return instance;
  };

  // OOP
  // ---------------
  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the
  // underscore functions. Wrapped objects may be chained.

  // Helper function to continue chaining intermediate results.
  var result = function result(instance, obj) {
    return instance._chain ? _(obj).chain() : obj;
  };

  // Add your own custom functions to the Underscore object.
  _.mixin = function (obj) {
    _.each(_.functions(obj), function (name) {
      var func = _[name] = obj[name];
      _.prototype[name] = function () {
        var args = [this._wrapped];
        push.apply(args, arguments);
        return result(this, func.apply(_, args));
      };
    });
  };

  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);

  // Add all mutator Array functions to the wrapper.
  _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function (name) {
    var method = ArrayProto[name];
    _.prototype[name] = function () {
      var obj = this._wrapped;
      method.apply(obj, arguments);
      if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
      return result(this, obj);
    };
  });

  // Add all accessor Array functions to the wrapper.
  _.each(['concat', 'join', 'slice'], function (name) {
    var method = ArrayProto[name];
    _.prototype[name] = function () {
      return result(this, method.apply(this._wrapped, arguments));
    };
  });

  // Extracts the result from a wrapped and chained object.
  _.prototype.value = function () {
    return this._wrapped;
  };

  // Provide unwrapping proxy for some methods used in engine operations
  // such as arithmetic and JSON stringification.
  _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;

  _.prototype.toString = function () {
    return '' + this._wrapped;
  };

  // AMD registration happens at the end for compatibility with AMD loaders
  // that may not enforce next-turn semantics on modules. Even though general
  // practice for AMD registration is to be anonymous, underscore registers
  // as a named module because, like jQuery, it is a base library that is
  // popular enough to be bundled in a third party lib, but not be part of
  // an AMD load request. Those cases could generate an error when an
  // anonymous define() is called outside of a loader request.
  if (typeof define === 'function' && define.amd) {
    define('underscore', [], function () {
      return _;
    });
  }
}).call(undefined); 
 			}); 		define("utils/util.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var T;
var utils = T = {
    extend: function extend(obj1, obj2, isDeep) {
        if (isDeep) {
            return utils.extrendDeep(obj1, obj2);
        }

        var obj = {};
        for (var p in obj1) {
            if (obj1.hasOwnProperty(p)) {
                obj[p] = obj1[p];
            }
        }
        for (var p in obj2) {
            if (obj2.hasOwnProperty(p)) {
                obj[p] = obj2[p];
            }
        }
        return obj;
    },
    extrendDeep: function extrendDeep(obj1, obj2) {
        //关联
        obj1 = obj1 || {};
        for (var p in obj2) {
            if (obj2.hasOwnProperty(p)) {
                obj1[p] = obj2[p];
            }
        }
        return obj1;
    },
    pluck: function pluck(objArray, key) {
        var values = [];
        if (!key) {
            return objArray;
        }

        try {
            var temp;
            var item;
            for (var i = 0, len = objArray.length; i < len; i++) {
                item = objArray[i];
                temp = key instanceof Array ? item[key[0]][key[1]] : item[key];
                if (temp === undefined) {
                    continue;
                }
                values.push(temp);
            }
            return values;
        } catch (e) {
            return values;
        }
        return values;
    },

    date: {
        fixDate: function fixDate(num) {
            return num < 10 ? '0' + num : num;
        },
        dateDifference: function dateDifference(startTime, endTime) {
            //获取两个时间点的天数差
            var start = new Date(this.compatibleDateFormat(startTime)),
                end = new Date(this.compatibleDateFormat(endTime));
            return Math.floor((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
        },
        compatibleDateFormat: function compatibleDateFormat(time) {
            var time = time || '';
            return time.replace(/-/g, '/');
        },
        getDateString: function getDateString(createTime) {
            var date = new Date(createTime);
            return this.fixDate(date.getMonth() + 1) + '/' + this.fixDate(date.getDate()) + ' ' + this.fixDate(date.getHours()) + ':' + this.fixDate(date.getMinutes());
        }
    },
    each: function each(arr, callback) {
        arr = arr || [];
        for (var i = 0; i < arr.length; i++) {
            callback && callback(arr[i], i);
        }
    },
    isArray: function isArray(obj) {
        return toString.call(obj) === '[object Array]';
    },
    isUndefined: function isUndefined(obj) {
        return obj === void 0;
    },
    isEmpty: function isEmpty(obj) {
        if (obj == null) return true;
        if (T.isNumber(obj)) return false;
        if (obj === true || obj === false) return false;
        if (utils.isArray(obj) || typeof obj === "string") {
            return obj.length === 0;
        }
        return Object.keys(obj).length === 0;
    },
    isObject: function isObject(obj) {
        var type = typeof obj === 'undefined' ? 'undefined' : _typeof(obj);
        return type === 'function' || type === 'object' && !!obj;
    },
    clone: function clone(obj) {
        if (!utils.isObject(obj)) return obj;
        if (T.isArray(obj) && T.isObject(obj[0])) {
            return T.copy(obj);
        }
        return utils.isArray(obj) ? obj.slice() : utils.extend({}, obj);
    },
    copy: function copy(arr) {
        arr = arr || [];
        var array = [];
        for (var i = 0; i < arr.length; i++) {
            array[i] = T.clone(arr[i]);
        }
        return array;
    },

    formatDate: function formatDate(format, date) {
        //   "yyyy-MM-dd hh:mm:ss"
        if (!date) return "";
        date = new Date(date);
        var o = {
            "M+": date.getMonth() + 1, //month
            "d+": date.getDate(), //day
            "h+": date.getHours(), //hour
            "m+": date.getMinutes(), //minute
            "s+": date.getSeconds(), //second
            "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
            "S": date.getMilliseconds(), //millisecond
            "w": "日一二三四五六".charAt(date.getDay())
        };
        format = format.replace(/y{4}/i, date.getFullYear()).replace(/y{2}/i, date.getFullYear().toString().substring(2));

        for (var k in o) {
            var reg = new RegExp(k);
            format = format.replace(reg, match);
        }

        function match(m) {
            return m.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length);
        }
        return format;
    },
    intersection: function intersection(array) {
        var result = [];
        var argsLength = arguments.length;
        for (var i = 0, length = T.getLength(array); i < length; i++) {
            var item = array[i];
            if (T.contains(result, item)) continue;
            for (var j = 1; j < argsLength; j++) {
                if (!T.contains(arguments[j], item)) break;
            }
            if (j === argsLength) result.push(item);
        }
        return result;
    },
    max: function max(obj, iteratee, context) {
        var result = -Infinity,
            lastComputed = -Infinity,
            value,
            computed;
        if (iteratee == null && obj != null) {
            obj = isArrayLike(obj) ? obj : T.values(obj);
            for (var i = 0, length = obj.length; i < length; i++) {
                value = obj[i];
                if (value > result) {
                    result = value;
                }
            }
        } else {
            iteratee = cb(iteratee, context);
            T.each(obj, function (value, index, list) {
                computed = iteratee(value, index, list);
                if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
                    result = value;
                    lastComputed = computed;
                }
            });
        }
        return result;
    },
    min: function min(obj, iteratee, context) {
        var result = Infinity,
            lastComputed = Infinity,
            value,
            computed;
        if (iteratee == null && obj != null) {
            obj = isArrayLike(obj) ? obj : T.values(obj);
            for (var i = 0, length = obj.length; i < length; i++) {
                value = obj[i];
                if (value < result) {
                    result = value;
                }
            }
        } else {
            iteratee = cb(iteratee, context);
            T.each(obj, function (value, index, list) {
                computed = iteratee(value, index, list);
                if (computed < lastComputed || computed === Infinity && result === Infinity) {
                    result = value;
                    lastComputed = computed;
                }
            });
        }
        return result;
    },
    contains: function contains(obj, item, fromIndex, guard) {
        if (!isArrayLike(obj)) obj = T.values(obj);
        if (typeof fromIndex != 'number' || guard) fromIndex = 0;
        return obj.indexOf(item, fromIndex) >= 0;
    },
    property: function property(key) {
        return function (obj) {
            return obj == null ? void 0 : obj[key];
        };
    },
    getLength: function getLength() {
        return T.property('length');
    },
    isNaN: function isNaN(obj) {
        return T.isNumber(obj) && obj !== +obj;
    },
    isNumber: function isNumber(obj) {
        return toString.call(obj) === '[object Number]';
    },
    isArrayLike: function isArrayLike(collection) {
        var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
        var length = T.getLength(collection);
        return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
    },
    values: function values(obj) {
        var keys = T.keys(obj);
        var length = keys.length;
        var values = Array(length);
        for (var i = 0; i < length; i++) {
            values[i] = obj[keys[i]];
        }
        return values;
    },
    keys: function keys(obj) {
        if (!T.isObject(obj)) return [];
        if (nativeKeys) return nativeKeys(obj);
        var keys = [];
        for (var key in obj) {
            if (T.has(obj, key)) keys.push(key);
        } // Ahem, IE < 9.
        if (hasEnumBug) collectNonEnumProps(obj, keys);
        return keys;
    },
    has: function has(obj, key) {
        return obj != null && hasOwnProperty.call(obj, key);
    },
    findIndex: createPredicateIndexFinder(1),
    sortedIndex: createPredicateIndexFinder(-1),
    indexOf: function indexOf() {
        return createIndexFinder(1, T.findIndex, T.sortedIndex);
    },
    getAttrObject: function getAttrObject(objArray, key, value) {
        //一个对象数组，获取key等于value的对象数组
        objArray = objArray instanceof Array ? objArray : [objArray];

        var arr = [];
        var item;
        var temp;
        for (var i = 0; i < objArray.length; i++) {
            item = objArray[i];
            if (item == undefined) {
                continue;
            }
            temp = key instanceof Array ? item[key[0]][key[1]] : item[key];

            if (value instanceof Array) {
                if (value.indexOf(temp) > -1) {
                    arr.push(item);
                }
            } else {
                if (temp == value) {
                    arr.push(item);
                }
            }
        }

        return arr;
    },
    isIdCard: function isIdCard(value) {
        value = value + "";
        var num = value.toUpperCase();
        if (!/(^\d{17}([0-9]|X)$)/.test(num)) {
            return false;
        }

        var len, re;
        len = num.length;
        if (len == 18) {
            re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
            var arrSplit = num.match(re);
            var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
            var bGoodDay;
            bGoodDay = dtmBirth.getFullYear() == Number(arrSplit[2]) && dtmBirth.getMonth() + 1 == Number(arrSplit[3]) && dtmBirth.getDate() == Number(arrSplit[4]);
            if (!bGoodDay) {
                return false;
            } else {
                var valnum;
                var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                var nTemp = 0,
                    i;
                for (i = 0; i < 17; i++) {
                    nTemp += num.substr(i, 1) * arrInt[i];
                }
                valnum = arrCh[nTemp % 11];
                if (valnum != num.substr(17, 1)) {
                    return false;
                }
                return true;
            }
        }
        return false;
    },
    getBirthdateAndSexByCardNumber: function getBirthdateAndSexByCardNumber(cardId) {
        var birth = cardId.substr(6, 8);
        birth = T.formatBirthdate(birth);
        var sex = cardId.substr(16, 1) % 2;
        return {
            birthdate: birth,
            sex: sex
        };
    },
    formatBirthdate: function formatBirthdate(dateStr) {
        //20140513 -->   2014-05-13
        if (dateStr.length === 8) {
            var reg = new RegExp('^(\\d{4})(\\d{2})(\\d{2})$');
            var result = reg.exec(dateStr);
            return result.splice(1, 3).join("-");
        }

        return dateStr;
    },

    showTips: function showTips(msg) {
        wx.showModal({
            showCancel: false,
            confirmColor: "#fd8041",
            content: msg,
            success: function success() {}
        });
    },
    showLoading: function showLoading() {
        wx.showToast({
            title: '努力加载中...',
            mask: true,
            duration: 10000,
            icon: 'loading'
        });
    },
    hideLoading: function hideLoading() {
        wx.hideToast();
    },
    //刷新
    refresh: function refresh() {
        wx.stopPullDownRefresh();
    },
    htmlToText: function htmlToText(data, key) {
        if (T.isEmpty(data)) {
            return data;
        }
        var reg = /<[^<]*>/gi;
        if (typeof data == "string") {
            return data.replace(reg, "");
        }
        if (T.isArray(data)) {
            data.forEach(function (item, i) {
                if (typeof data[i] == "string") {
                    data[i] = data[i].replace(reg, "");
                }
                if (T.isObject(data[i])) {
                    data[i][key] = data[i][key].replace(reg, "");
                }
            });
        }
        return data;
    },
    getPayText: function getPayText(data) {
        var payStatus = data.payStatus; //支付状态(0未支付  1已支付 2不能支付 3扣款中 4扣款失败 5扣款成功)
        var issueStatus = data.issueStatus; //出单状态(0未出单 1已出单 2延时出单 3取消出单)
        var effectiveStatus = data.effectiveStatus; ////0 未生效  1 已生效   2 退保中  3 已退保（撤销）

        var payText = "";
        data.isEffect = new Date(data.startDate.replace(/-/g, '/') || '') <= new Date() ? true : false;
        if (data.createTime.substr(0, 10) == T.formatDate('yyyy-MM-dd', new Date())) {
            data.isEffect = new Date(data.startDate.substr(0, 10).replace(/-/g, '/') + " 23:30:00") < new Date() ? true : false;
        }
        if (payStatus === 0) {
            if (data.isEffect) {
                payText = "未支付-已过期";
            } else {
                payText = "未支付";
            }
        } else {
            if (payStatus === 3) {
                payText = "扣款中";
            } else if (payStatus === 4) {
                payText = "扣款失败";
            } else if (payStatus === 5) {
                payText = "扣款成功";
            } else {
                //出单状态
                if (issueStatus === 0) {
                    payText = "待出单";
                } else if (issueStatus == 1) {
                    payText = "已出单";
                }

                //退保状态
                if (effectiveStatus == 2) {
                    payText = "退保中";
                } else if (effectiveStatus == 3) {
                    payText = "已退保";
                }
            }
        }

        return payText;
    }
};

function createIndexFinder(dir, predicateFind, sortedIndex) {
    return function (array, item, idx) {
        var i = 0,
            length = T.getLength(array);
        if (typeof idx == 'number') {
            if (dir > 0) {
                i = idx >= 0 ? idx : Math.max(idx + length, i);
            } else {
                length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
            }
        } else if (sortedIndex && idx && length) {
            idx = sortedIndex(array, item);
            return array[idx] === item ? idx : -1;
        }
        if (item !== item) {
            idx = predicateFind(slice.call(array, i, length), T.isNaN);
            return idx >= 0 ? idx + i : -1;
        }
        for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
            if (array[idx] === item) return idx;
        }
        return -1;
    };
}

function createPredicateIndexFinder(dir) {
    return function (array, predicate, context) {
        predicate = cb(predicate, context);
        var length = T.getLength(array);
        var index = dir > 0 ? 0 : length - 1;
        for (; index >= 0 && index < length; index += dir) {
            if (predicate(array[index], index, array)) return index;
        }
        return -1;
    };
}

module.exports = utils; 
 			}); 		define("app.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

var api = require('utils/api.js');
var Q = require("utils/q.js");

App({
  systemInfo: null,
  sid: '',
  defaultId: 1000001,
  partnerId: '',
  payState: [{ id: 1, name: '全部', value: '' }, { id: 2, name: '未支付', value: 0 }, { id: 3, name: '已支付', value: 1 }, { id: 4, name: '已出单', value: 2 }, { id: 5, name: '已过期', value: 3 }, { id: 6, name: '已退保', value: 4 }],
  onLaunch: function onLaunch(option) {
    var self = this;
    option = option || {};
    wx.getSystemInfo({
      success: function success(res) {
        self.systemInfo = res;
      }
    });
    self.partnerId = wx.getStorageSync('partnerId');
    if (!self.partnerId) {
      self.partnerId = self.defaultId;
    }
  },
  checkSession: function checkSession() {
    var self = this;
    var def = Q.defer();
    wx.checkSession({
      success: function success() {
        //登录态未过期
        var sid = wx.getStorageSync('sid');
        if (sid) {
          self.sid = sid;
          def.resolve();
        } else {
          self.login(function () {
            def.resolve();
          });
        }
      },
      fail: function fail() {
        self.login(function () {
          def.resolve();
        });
      }
    });
    return def.promise;
  },
  login: function login(cb) {
    var self = this;
    //登录态过期
    wx.login({
      success: function success(res) {
        wx.getUserInfo({
          success: function success(res) {
            self.globalData.userInfo = res.userInfo;
          }
        });
        if (res.code) {
          api.jscode2session({
            data: {
              code: res.code
            },
            success: function success(res) {
              try {
                wx.setStorageSync('sid', res.data);
                self.sid = res.data;
                cb && cb();
              } catch (e) {}
            }
          });
        } else {
          wx.showToast({
            title: '失败',
            icon: 'error',
            duration: 2000
          });
          cb && cb();
        }
      }
    });
  },
  clearSid: function clearSid() {
    wx.setStorageSync('sid', '');
  },
  setPartnerId: function setPartnerId(partnerId) {
    this.partnerId = partnerId;
    wx.setStorageSync('partnerId', partnerId);
  },
  getUserInfo: function getUserInfo(cb) {
    var that = this;
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo);
    } else {
      //调用登录接口
      wx.login({
        success: function success() {
          wx.getUserInfo({
            success: function success(res) {
              that.globalData.userInfo = res.userInfo;
              typeof cb == "function" && cb(that.globalData.userInfo);
            }
          });
        }
      });
    }
  },
  globalData: {
    userInfo: null,
    tobeTempData: {},
    trialGenes: ''
  }
}); 
 			}); 	require("app.js");
 		__wxRoute = 'pages/home/home';__wxRouteBegin = true; 	define("pages/home/home.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

var api = require('../../utils/api.js');
var utils = require('../../utils/util.js');
var _ = require("../../utils/underscore");
var App = getApp();

Page({
	data: {
		firstLoading: true
	},
	onLoad: function onLoad(options) {
		var partnerId = options.partnerId;
		if (partnerId > 0) {
			App.setPartnerId(partnerId);
		}
	},
	onReady: function onReady() {
		// 页面渲染完成
		var _this = this;
		// App.login().then(function () {
		_this.getProductList();
		// })
	},
	onShow: function onShow() {
		// 页面显示
	},
	onHide: function onHide() {
		// 页面隐藏
	},
	onUnload: function onUnload() {
		// 页面关闭
	},
	//下拉刷新
	onPullDownRefresh: function onPullDownRefresh() {
		this.getProductList();
	},
	onShareAppMessage: function onShareAppMessage() {
		return {
			title: '微金保--随时随地买保险',
			desc: '微金保--随时随地买保险',
			path: 'pages/home/home?uid=' + App.partnerId
		};
	},
	//获取列表数据
	getProductList: function getProductList() {
		utils.showLoading();
		var _this = this;
		api.getProductList({
			data: {
				partnerId: App.partnerId
			},
			success: function success(result) {
				_this.formatData(result.data);
				console.log(result.data);
				_this.setData({
					list: result.data
				});
			},
			complete: function complete() {
				_this.setData({ firstLoading: false });
				utils.hideLoading();
				wx.stopPullDownRefresh();
			}
		});
	},
	formatData: function formatData(data) {
		data = data || [];
		var featureList;
		data.forEach(function (item, index) {
			featureList = item.detail.featureList || [];
			featureList.forEach(function (fItem, i) {
				featureList[i].content = fItem.content && fItem.content.replace(/<[^<]*>/gi, "  ") || "";
			});
		});
	},
	//页面跳转
	goTo: function goTo(ev) {
		var ds = ev.currentTarget.dataset;
		wx.navigateTo({
			url: '/pages/product/detail/detail?productId=' + ds.productid + '&planId=' + ds.planid + '&img=' + ds.img
		});
	}
}); 
 			}); 	require("pages/home/home.js");
 		__wxRoute = 'pages/order/list/list';__wxRouteBegin = true; 	define("pages/order/list/list.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

/**
 * @name 订单列表
 * @description 订单列表
 * @author kingwell
 * @date 2017/1/18; 
 */
var _ = require('../../../utils/underscore');
var moment = require("../../../utils/moment");
var api = require('../../../utils/api.js');
var utils = require('../../../utils/util.js');
var App = getApp();

Page({
	data: {
		windowWidth: App.systemInfo.windowWidth,
		windowHeight: App.systemInfo.windowHeight,
		scrollTop: 0,
		pageIndex: 0,
		pageSize: 20,
		list: [],
		loading: false,
		noMore: false,
		currentTabId: 1
	},
	onLoad: function onLoad() {
		this.loadMore();

		wx.setNavigationBarTitle({
			title: '我的订单'
		});
	},
	onShow: function onShow() {
		this.setData({
			pageIndex: 0
		});
		this.loadMore(null, true);
	},
	onPullDownRefresh: function onPullDownRefresh() {
		this.setData({
			pageIndex: 0
		});
		this.loadMore(null, true);
	},
	loadMore: function loadMore(params, needRefresh) {
		var self = this;
		var loading = self.data.loading;
		var payState = App.payState;
		var currentTabId = self.data.currentTabId;
		if (loading) {
			return;
		}
		if (!self.data.noMore || needRefresh) {
			self.setData({
				loading: true
			});
			params = { state: _.find(payState, { id: currentTabId }).value, pageModel: { pageIndex: self.data.pageIndex + 1, pageSize: self.data.pageSize } };
			if (needRefresh) utils.showLoading();
			//获取订单列表
			api.orderList({
				data: params,
				method: 'POST',
				success: function success(result) {
					var newList = result.data.data || [];
					_.each(newList, function (item, index) {
						item.stateText = _.find(payState, { value: item.state }).name;
						item.realPrice = (item.realPrice / 100).toFixed(2);
						//投保日期
						item.createTimeString = moment(item.createTime).format('YYYY-MM-DD');
						//起保日期
						item.startTimeString = moment(item.startDate).format('YYYY-MM-DD');
						//截止日期
						item.endTimeString = moment(item.endDate).format('YYYY-MM-DD');

						item.isEffect = new Date(item.startDate.replace(/-/g, '/')) < new Date() ? true : false;
						if (item.createTimeString == moment(new Date()).format('YYYY-MM-DD')) {
							item.isEffect = new Date(item.startTimeString.replace(/-/g, '/') + " 23:30:00") < new Date() ? true : false;
						}
						if (item.isEffect && item.state == 0) {
							item.stateText = "未支付-已过期";
						}
					});
					if (needRefresh) {
						wx.stopPullDownRefresh();
					} else {
						newList = self.data.list.concat(newList);
					}
					console.log(newList);
					self.setData({
						list: newList,
						pageIndex: result.data.pageIndex,
						noMore: result.data.pageIndex >= result.data.pageNums
					});
				},
				complete: function complete(result) {
					self.setData({
						loading: false
					});
					utils.hideLoading();
				}
			});
		}
	},
	//Tab切换
	tabChange: function tabChange(ev) {
		var ds = ev.currentTarget.dataset;
		this.setData({
			scrollTop: 0,
			pageIndex: 0,
			currentTabId: parseInt(ds.current)
		});
		this.loadMore(null, true);
	},
	setTab: function setTab(val) {
		this.setData({
			currentTab: val,
			tabContent: val
		});
	},
	handletouchend: function handletouchend() {
		this.data.touchStatus = true;
	},
	handletouchtart: function handletouchtart(event) {
		this.data.lastX = event.touches[0].pageX;
		this.data.lastY = event.touches[0].pageY;
		this.data.touchStatus = false;
	},
	handletouchmove: function handletouchmove(event) {
		var currentX = event.touches[0].pageX,
		    currentY = event.touches[0].pageY,
		    tx = currentX - this.data.lastX,
		    ty = currentY - this.data.lastY,
		    text = "",
		    val = this.data.currentTab;

		if (this.data.touchStatus) {
			return;
		}
		this.data.touchStatus = true;

		if (Math.abs(tx) > Math.abs(ty)) {
			//左右方向滑动
			if (tx < 0) {
				//text = "向左滑动";
				val++;
				if (val >= 3) {
					val = 3;
				}
			} else if (tx > 0) {
				//text = "向右滑动";				
				val--;
				if (val <= 0) {
					val = 0;
				}
			}
		}
		//上下方向滑动
		// else {
		// 	if (ty < 0) {
		// 		text = "向上滑动"
		// 	} else if (ty > 0) {
		// 		text = "向下滑动"
		// 	}
		// }

		if (val !== '') {
			this.setTab(val.toString());
		}
		//console.log(text);
	},
	//页面跳转
	goTo: function goTo(ev) {
		var data = ev.currentTarget.dataset;
		var url = '/pages/order/detail/detail?id=' + data.id;
		wx.navigateTo({
			url: url
		});
	}
}); 
 			}); 	require("pages/order/list/list.js");
 		__wxRoute = 'pages/order/detail/detail';__wxRouteBegin = true; 	define("pages/order/detail/detail.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

var _ = require('../../../utils/underscore');
var moment = require("../../../utils/moment");
var api = require('../../../utils/api.js');
var utils = require('../../../utils/util.js');
var App = getApp();

Page({
  data: {
    windowWidth: App.systemInfo.windowWidth,
    windowHeight: App.systemInfo.windowHeight,
    loading: false,
    firstLoading: true,
    order: {}
  },
  onLoad: function onLoad(options) {
    console.log(options);
    this.setData({
      encryptInsureNum: options.id
    });
    this.load();
  },
  onPullDownRefresh: function onPullDownRefresh() {
    this.load();
  },
  load: function load() {
    var payState = App.payState;
    utils.showLoading();
    var self = this;
    api.getOrderDetail({
      data: { encryptInsureNum: self.data.encryptInsureNum },
      success: function success(result) {
        self.setData({ firstLoading: false });
        utils.hideLoading();
        var item = result.data;
        item.payText = item.payText || utils.getPayText(item);

        self.setData({
          order: _.extend(item, { createTime: moment(item.createTime).format('YYYY-MM-DD HH:mm'), payAmountStr: (item.payAmount / 100).toFixed(2) })
        });
        console.log(self.data.order, "aaaaaaaaaa");
      }
    });
  },
  paying: function paying() {
    var self = this;
    wx.navigateTo({
      url: '/pages/product/pay/pay?id=' + self.data.encryptInsureNum
    });
    // const self = this;
    // const bool = self.data.loading;
    // if (!bool) {
    //   self.setData({
    //     loading: true
    //   })
    //   api.paying({
    //     data: {
    //       gatewayMoney: self.data.order.payAmount,
    //       insureNum: self.data.encryptInsureNum,
    //       partnerId: App.partnerId
    //     },
    //     success: function (result) {
    //       wx.requestPayment({
    //         'timeStamp': result.data.gatewayData.timeStamp,
    //         'nonceStr': result.data.gatewayData.nonceStr,
    //         'package': result.data.gatewayData.package,
    //         'signType': result.data.gatewayData.signType,
    //         'paySign': result.data.gatewayData.paySign,
    //         'success': function (res) {
    //           self.setData({
    //             loading: false
    //           })
    //           wx.redirectTo({
    //             url: '/pages/product/success/success?id=' + self.data.encryptInsureNum
    //           })
    //         },
    //         'fail': function (res) {
    //           self.setData({
    //             loading: false
    //           })
    //           console.log(res);
    //         }
    //       })
    //     }
    //   })
    // }
  },
  //查看保单
  viewOrder: function viewOrder() {
    // wx.navigateTo({
    //   url: '/pages/order/order/order'
    // });
    var self = this;
    utils.showLoading();
    wx.downloadFile({
      url: api.apiURL + '/order/preview.pdf?sid=' + App.sid + '&id=' + self.data.encryptInsureNum,
      success: function success(res) {
        var filePath = res.tempFilePath;
        wx.openDocument({
          filePath: filePath,
          success: function success(res) {
            console.log('打开文档成功');
            console.log(res);
          },
          fail: function fail(res) {
            console.log('fail');
            console.log(res);
          },
          complete: function complete(res) {
            console.log('complete');
            console.log(res);
          }
        });
      },
      fail: function fail(res) {
        console.log('fail');
        console.log(res);
      },
      complete: function complete(res) {
        utils.hideLoading;
        console.log('complete');
        console.log(res);
      }
    });
  }
}); 
 			}); 	require("pages/order/detail/detail.js");
 		__wxRoute = 'pages/order/send/send';__wxRouteBegin = true; 	define("pages/order/send/send.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

// pages/order/detail/detail.js

Page({
  data: {
    disabled: true
  },
  onLoad: function onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
    wx.setNavigationBarTitle({
      title: '发送保单'
    });
  },
  onReady: function onReady() {
    // 页面渲染完成
  },
  onShow: function onShow() {
    // 页面显示
  },
  onHide: function onHide() {
    // 页面隐藏
  },
  onUnload: function onUnload() {

    // 页面关闭
  },
  validateHandle: function validateHandle(ev) {
    var reg = /^[a-zA-Z0-9][a-zA-Z0-9._-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    var status = reg.test(ev.detail.value);
    this.setData({
      disabled: !status
    });
  },
  submitHandle: function submitHandle(ev) {

    wx.showToast({
      title: ev.detail.value.email,
      icon: 'success',
      duration: 2000
    });
  }
}); 
 			}); 	require("pages/order/send/send.js");
 		__wxRoute = 'pages/order/order/order';__wxRouteBegin = true; 	define("pages/order/order/order.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

// pages/order/order/order.js
Page({
  data: {},
  onLoad: function onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
    wx.setNavigationBarTitle({
      title: '发送保单'
    });
  },
  onReady: function onReady() {
    // 页面渲染完成
  },
  onShow: function onShow() {
    // 页面显示
  },
  onHide: function onHide() {
    // 页面隐藏
  },
  onUnload: function onUnload() {
    // 页面关闭
  },
  sendHandle: function sendHandle() {
    wx.showToast({
      title: '已发送',
      icon: 'success',
      duration: 2000
    });
  }
}); 
 			}); 	require("pages/order/order/order.js");
 		__wxRoute = 'pages/product/index/index';__wxRouteBegin = true; 	define("pages/product/index/index.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

var App = getApp();
var api = require('../../../utils/api.js');
var util = require('../../../utils/util.js');

var formatTime = util.formatTime;

Page({
  data: {
    trips: [],
    start: 0,
    loading: false
  },
  onLoad: function onLoad() {
    this.loadMore();
  },
  onPullDownRefresh: function onPullDownRefresh() {
    this.loadMore(null, true);
  },
  loadMore: function loadMore(e, needRefresh) {
    var self = this;
    var loading = self.data.loading;
    var data = {
      partnerId: 1000034,
      next_start: self.data.start
    };
    if (loading) {
      return;
    }
    self.setData({
      loading: true
    });
    api.getProductList({
      data: data,
      success: function success(res) {
        var newList = res.data;
        newList.map(function (trip) {
          var item = trip;
          return item;
        });
        if (needRefresh) {
          wx.stopPullDownRefresh();
        } else {
          newList = self.data.trips.concat(newList);
        }
        self.setData({
          trips: newList
        });
        var nextStart = res.data.next_start;
        self.setData({
          start: nextStart,
          loading: false
        });
      }
    });
  },
  viewTrip: function viewTrip(e) {
    var ds = e.currentTarget.dataset;
    wx.navigateTo({
      url: '../detail/detail?productId=' + ds.productId + '&planId=' + ds.planId
    });
  }
}); 
 			}); 	require("pages/product/index/index.js");
 		__wxRoute = 'pages/product/detail/detail';__wxRouteBegin = true; 	define("pages/product/detail/detail.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

var api = require("../../../utils/api");
var util = require("../../../utils/util");
var T = util;
var Trial = require("../../../utils/trial-core");
var _ = require("../../../utils/underscore");

var app = getApp();

var selectedKey = '';
var selectedVal = '';
var _option = {};

Page({
  data: {
    firstLoading: true,
    showTrial: false,
    product: {},
    text: {},
    protectItemList: [],
    insurantDateAllDes: "",
    insurantDateLimitAllDes: ""
  },
  onLoad: function onLoad(option) {
    var partnerId = option.partnerId;
    if (partnerId > 0) {
      app.setPartnerId(partnerId);
    }
    this.init(option);
  },
  onShow: function onShow() {
    var self = this;
    if (!self.data.firstLoading) {
      Trial.setReady(self.ready);
      Trial.setOnChange(self.onChange);
    }
  },
  onShareAppMessage: function onShareAppMessage() {
    return {
      title: this.data.product.name || "微金保--随时随地买保险",
      desc: '',
      path: 'pages/product/detail/detail?partnerId=' + app.partnerId + "&productId=" + _option.productId + "&planId=" + _option.planId
    };
  },
  init: function init(option) {
    _option = option;
    util.showLoading();
    Trial.reset();
    var self = this;
    Trial.config({
      uid: app.partnerId,
      debug: true,
      productId: option.productId,
      planId: option.planId,
      ready: self.ready,
      onChange: self.onChange
    });
  },
  ready: function ready(err, data) {
    var self = this;
    self.setData({ firstLoading: false });
    setTimeout(function () {
      util.hideLoading();
    }, 500);
    var text = Trial.getResultData().text;
    text.featureList = T.htmlToText(text.featureList, "content");
    text.hzinsTips = T.htmlToText(text.hzinsTips);
    app.globalData.hzinsTips = text.hzinsTips || [];
    self.setData({
      product: _.extend(Trial.getResultData().product, { id: _option.productId, planId: _option.planId, price: Trial.getTrialPrice() }),
      text: text,
      detail: Trial.getResultData().detail,
      protectItemList: Trial.getProtectItem(),
      geneList: self.procGeneList(data.geneList)
    });
    self.setAllDescribe(data.geneList);

    console.log("全数据：", Trial.getResultData());
  },
  onChange: function onChange(err, data) {
    var self = this;
    self.setData({
      product: _.extend(self.data.product, { price: Trial.getTrialPrice() })
    });
    if (data.geneList && data.geneList.length != 0) {
      self.setData({
        geneList: self.procGeneList(data.geneList)
      });
    } else {
      var geneList = self.data.geneList;
      _.each(geneList, function (item, index) {
        _.each(item.valueList, function (subItem, subIndex) {
          if (item.key == selectedKey) {
            subItem.selected = false;
            if (subItem.valueStr == selectedVal) subItem.selected = true;
          }
        });
      });
      self.setData({
        geneList: geneList
      });
    }
    util.hideLoading();
  },

  procGeneList: function procGeneList(geneList) {
    var newGeneList = [];
    _.each(geneList, function (item, index) {
      var key = item.key ? item.key : item.geneKey;
      var newGene = {};
      newGene.id = item.id;
      newGene.key = key;
      newGene.name = item.name;
      if (item.dictionaryList) {
        var valueList = [];
        var index = 0,
            maxIndex = 5,
            dataList = [];
        _.each(item.dictionaryList, function (subItem, subIndex) {
          if (subItem.type == 2) {
            var min = subItem.min,
                max = subItem.max,
                step = subItem.step,
                unit = subItem.unit,
                unitStr = Trial.transUnit(subItem.unit);
            for (; min <= max || min - step < max; min = min + step, index++) {
              var val = min + unitStr;
              if (min <= max) val = min + unitStr;else val = max + unitStr;
              var select = val == item.defaultValue;
              var value = {};
              value.value = val;
              value.unit = subItem.unit;
              value.valueStr = val;
              value.selected = select;
              valueList.push(value);
              index++;
            }
          } else {
            var unitStr = Trial.transUnit(subItem.unit);
            var val = (subItem.value ? subItem.value : subItem.defaultValue) + (unitStr ? unitStr : '');
            var select = val == item.defaultValue;

            var value = {};
            value.value = subItem.value ? subItem.value : subItem.defaultValue;
            value.unit = subItem.unit;
            value.valueStr = val;
            value.selected = select;
            valueList.push(value);
            index++;
          }
        });
        newGene.valueList = valueList;
        newGeneList.push(newGene);
      }
    });
    return newGeneList;
  },
  setAllDescribe: function setAllDescribe(data) {
    var data = data || [];
    data = data || [];
    var item, itemId;
    var allDes,
        obj = {};;
    for (var i = 0; i < data.length; i++) {
      item = data[i];
      itemId = item.geneKey || item.key;
      var dictionaryList = item.dictionaryList || [];
      if (itemId == "insurantDate" || itemId == "insurantDateLimit") {
        if (item.rangeDic) {
          if (item.rangeDic.value) {
            allDes = item.rangeDic.value + Trial.transUnit(item.rangeDic.unit);
          } else {
            allDes = item.rangeDic.min + "-" + item.rangeDic.max + Trial.transUnit(item.rangeDic.unit);
            if (item.rangeDic.max && (item.rangeDic.max + "").indexOf("至") == 0) {
              allDes = item.rangeDic.max + Trial.transUnit(item.rangeDic.unit) + "可选";
            }
          }
        } else {
          allDes = dictionaryList[0].value + Trial.transUnit(dictionaryList[0].unit);
          if (dictionaryList.length > 1) {
            allDes = allDes + "-" + dictionaryList[dictionaryList.length - 1].value + Trial.transUnit(dictionaryList[dictionaryList.length - 1].unit);
            if (dictionaryList[dictionaryList.length - 1].value.indexOf("至") == 0) {
              allDes = dictionaryList[dictionaryList.length - 1].value + Trial.transUnit(dictionaryList[dictionaryList.length - 1].unit) + "可选";
            }
          }
        }
        if (dictionaryList.length > 1 && allDes.indexOf("可选") < 0) {
          allDes += "可选";
        }
        obj[itemId + "AllDes"] = allDes;
      }
    }
    this.setData(obj);
  },
  changeTrial: function changeTrial(e) {
    var ds = e.currentTarget.dataset;
    var key = ds.key;
    var unit = ds.unit;
    var val = ds.val;
    selectedKey = key;
    selectedVal = val.indexOf(Trial.transUnit(unit)) == -1 ? val + Trial.transUnit(unit) : val;
    Trial.setTrialVal(key, val.indexOf(Trial.transUnit(unit)) == -1 ? val + Trial.transUnit(unit) : val);
    util.showLoading();
    Trial.tryTrialPrice();
  },
  showDes: function showDes(e) {
    var des = e.currentTarget.dataset.des || "";
    if (des) {
      T.showTips(des);
    }
  },
  showTrial: function showTrial(e) {
    var self = this;
    self.setData({ showTrial: true });
  },
  closeTrial: function closeTrial(e) {
    var self = this;
    self.setData({ showTrial: false });
  },
  //打电话
  callTel: function callTel(ev) {
    wx.makePhoneCall({
      phoneNumber: ev.currentTarget.dataset.tel
    });
  },
  toInsure: function toInsure(e) {
    this.closeTrial();
    var ds = e.currentTarget.dataset;
    app.globalData.trialGenes = Trial.getTrialGenes();
    wx.navigateTo({
      url: '../insure/insure?productId=' + ds.prodId + '&planId=' + ds.planId
    });
  }
}); 
 			}); 	require("pages/product/detail/detail.js");
 		__wxRoute = 'pages/product/insure/insure';__wxRouteBegin = true; 	define("pages/product/insure/insure.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

var api = require("../../../utils/api");
var T = require("../../../utils/util");
var insureConfig = require("../../../utils/insure-config");
var Trial = require("../../../utils/trial-core");
var app = getApp();
var Param,
    insureData = {};
var moduleMap = {};
var tobeBySelfParam = {};
var opt;
var maxTobeNum;
var isTrying;
Page({
  data: {
    isDomReay: false,
    price: "",
    buyCount: 1,
    isToMySelf: true,
    isHaveToMySelf: false,

    toWhoData: {},
    startDateData: {},
    endDateData: {
      type: 3,
      disabled: true,
      value: "",
      name: "终保日期",
      hidden: false
    },
    product: {},
    modules: [],
    moduleMap: moduleMap,
    tobeData: {},
    tobeParam: [],
    selectedMap: {},
    config: insureConfig.renderConfg,
    dateLimitMap: {}
  },
  onLoad: function onLoad(option) {
    console.log("onload......");
    opt = option || {};
    Trial.reset();
    this.initTrial(option);

    wx.setNavigationBarTitle({
      title: '填写投保信息'
    });
  },
  onReady: function onReady() {
    console.log("onReady......");
  },
  onShow: function onShow() {
    isTrying = false;
    var tobeTempData = app.globalData.tobeTempData;
    console.log("onshow......", tobeTempData);
    if (!T.isEmpty(app.globalData.tobeTempData) && !T.isEmpty(tobeTempData.priceData)) {
      this.setData({
        tobeParam: tobeTempData.tobeParam || [],
        price: tobeTempData.priceData.totalPrice
      });
    }
  },

  onUnload: function onUnload() {
    console.log("onUnload............");
    app.globalData.tobeTempData = {};
  },
  readyAction: function readyAction() {
    var insurantDate = Trial.getTrialVal('insurantDateLimit') && Trial.getTrialVal('insurantDateLimit').value || "";
    if (insurantDate.indexOf("至") == 0 || insurantDate.indexOf("不限") > -1) {
      this.data.endDateData.hidden = true;
    }

    this.setData({
      endDateData: this.data.endDateData
    });
  },
  initInsure: function initInsure(_product, _insureModule, _sort) {
    //缓存数据
    maxTobeNum = _product.maxPeople || 1;
    app.globalData.insureDeclareContent = _product.insureDeclare || "";

    var startDateData = Trial.getStartDateData();
    this.data.endDateData.value = T.formatDate("yyyy-MM-dd", Trial.formatInsuranceDate(startDateData.start) || new Date(Trial.now()));
    Trial.setStartDate(T.formatDate("yyyy-MM-dd", startDateData.start));

    this.initParam(_insureModule);

    this.setData({
      isDomReay: true,
      product: _product,
      modules: _insureModule,
      moduleMap: moduleMap,
      tobeData: moduleMap["20"],
      toWhoData: Trial.getToWhoData(),
      startDateData: Trial.getStartDateData(),
      endDateData: this.data.endDateData,
      isToMySelf: Trial.supportSelf(),
      buyCount: Trial.getBuyCountData().default || 1
    });

    console.log(this.data);

    this.toWhoAction();

    app.globalData.tobeTempData = {
      tobeParam: [],
      applicantParam: insureData[10] && insureData[10][0] || {},
      config: this.data.config,
      tobeData: this.data.tobeData,
      selectedMapArr: []
    };
  },
  initTrial: function initTrial(option) {
    var that = this;
    Trial.reset();
    Trial.config({
      uid: app.partnerId,
      productId: option.productId,
      planId: option.planId,
      trialGenes: app.globalData.trialGenes ? JSON.parse(app.globalData.trialGenes) : "",

      ready: function ready(err, data) {
        console.log("初始化----", data);

        that.setData({ price: data.price });

        that.readyAction();
      },
      onChange: function onChange(err, data) {
        if (err) {
          T.showTips(err.msg);
          return;
        }
        console.log("onChange----", data);

        //P.actions.trialChangeAction(data.geneList);
        that.setData({
          price: data.price
        });
      },
      callback: {
        renderInsureAttr: function renderInsureAttr(err, _product, _insureModule, _sort) {
          moduleMap = _insureModule;
          var insureModules = that.sortInsureModules(_insureModule, _sort);
          that.initInsure(_product, insureModules, _sort);

          console.log("投保模块:", moduleMap, insureModules);
          console.log("产品详情——", _product);
        },

        showError: function showError(errorData) {
          var obj = errorData.errors;
          if (obj.errorMsg) {}
        }
      }
    });
  },
  sortInsureModules: function sortInsureModules(insureModule, sort) {
    sort = sort || [];
    var modules = [],
        index;
    for (var i = 0; i < sort.length; i++) {
      index = sort[i] + "";
      modules.push(insureModule[index]);
    }
    return modules;
  },
  deleteTobe: function deleteTobe(e) {
    var that = this;
    var dataset = e.currentTarget.dataset;
    if (this.data.tobeParam.length <= 1) {
      T.showTips("至少有1个被保险人");
      return;
    }
    wx.showModal({
      title: "删除被保险人",
      content: '确认删除被保险人  ' + dataset.name + "  ?",
      success: function success(res) {
        if (res.confirm) {

          var index = dataset.index;
          if (index !== undefined) {
            app.globalData.tobeTempData.tobeParam.splice(index, 1);
            app.globalData.tobeTempData.selectedMapArr.splice(index, 1);
            that.data.tobeParam.splice(index, 1);
            that.setData({
              tobeParam: that.data.tobeParam
            });
            that.tryInsurantPrice();
          }
        }
      }
    });
  },
  toAddTobePage: function toAddTobePage() {
    if (this.data.tobeParam.length >= maxTobeNum) {
      T.showTips("最多只能添加" + maxTobeNum + "个被保险人");
      return;
    }
    wx.navigateTo({
      url: '../insure-add/insure-add'
    });
  },

  initParam: function initParam(insureModule) {
    insureData = {};
    var items, item, i, j, obj, attr;
    for (i = 0; i < insureModule.length; i++) {
      items = insureModule[i];
      insureData[items.id] = [];
      attr = items.attr;
      if (items.id == 30 || items.id == 102) {
        //暂时固定为法定受益人
        continue;
      } else if (items.id == 20) {
        attr = items.attr.default;
      }
      obj = {};
      for (var key in attr) {
        item = attr[key];
        obj[item.keyCode] = "";

        if (item.type == 1) {
          //日历控件
          var limit = Trial.calculateDateLimit({
            mid: items.id,
            key: item.keyCode
          });
          item.start = T.formatDate("yyyy-MM-dd", limit.minDate);
          item.end = T.formatDate("yyyy-MM-dd", limit.maxDate);
          item.default = item.start;
          if (item.keyCode == "birthdate") {
            item.default = ""; //item.end;
          }
          this.data.dateLimitMap[items.id + item.keyCode] = {
            start: item.start,
            end: item.end,
            "default": item.default
          };

          obj[item.keyCode] = item.default;
          if (items.id == 20 && item.keyCode == "birthdate" && this.data.isToMySelf) {
            obj[item.keyCode] = insureData["10"][0].birthdate;
          }
        }

        if (item.values) {
          if (key !== "applicantType") {
            item.values = Trial.procRestricts(item.values, item.restricts || []) || [];
          }
        }
        if (item.values && item.values.length) {
          obj[item.keyCode] = item.values[0].controlValue;
        }
      }
      if (items.id == 20) {
        //先把被保险人的缓存起来  切换关系的时候有用到
        tobeBySelfParam = T.clone(obj);
        continue;
      }
      insureData[items.id].push(obj);
    }
  },
  resetDateLimit: function resetDateLimit(modules) {
    var items, item, i, j, obj, attr;
    for (i = 0; i < modules.length; i++) {
      items = modules[i];
      attr = items.attr;
      for (var key in attr) {
        item = attr[key];
        if (item.type == 1) {
          //日历控件
          var limit = Trial.calculateDateLimit({
            mid: items.id,
            key: item.keyCode
          });
          item.start = T.formatDate("yyyy-MM-dd", limit.minDate);
          item.end = T.formatDate("yyyy-MM-dd", limit.maxDate);
          item.default = item.start;
          if (item.keyCode == "birthdate") {
            item.default = ""; //item.end;
          }
          this.data.dateLimitMap[items.id + item.keyCode] = {
            start: item.start,
            end: item.end,
            "default": item.default
          };
        }
      }
    }
  },

  toWhoAction: function toWhoAction() {
    Trial.setInsurantSelf(this.data.isToMySelf);
    this.setData({
      isToMySelf: this.data.isToMySelf
    });
    this.setInsurantParam();

    if (this.data.isToMySelf && this.ifTobeReady()) {
      this.tryInsurantPrice();
    } else {
      this.onShow();
    }
  },
  setInsurantParam: function setInsurantParam() {
    if (this.data.isToMySelf) {
      insureData[20] = [];
      insureData[20][0] = T.clone(tobeBySelfParam) || {};
      insureData[20][0].price = this.data.price;
      insureData[20][0].relationInsureInsurant = 1;
      insureData[20][0].buyCount = this.data.buyCount;
    } else {
      insureData[20] = this.data.tobeParam;
    }
  },
  handleInsureParam: function handleInsureParam() {
    this.setInsurantParam();

    var startDate = Trial.getStartDate();
    var endDate = Trial.formatInsuranceDate(startDate) || new Date(Trial.now());
    insureData[102][0] = insureData[102][0] || {};
    insureData[102][0].startDate = T.formatDate("yyyy-MM-dd", startDate);
    insureData[102][0].endDate = T.formatDate("yyyy-MM-dd", endDate);

    return Trial.checkFormParam(insureData);
  },
  submitInsure: function submitInsure() {
    var that = this;
    if (isTrying) {
      T.showLoading();
      this.tryInsurantPrice(function () {
        T.hideLoading();
        requestAct();
      });
      return;
    } else {
      requestAct();
    }

    function requestAct() {
      if (!that.data.price || that.data.price === 0) {
        T.showTips("无法试算出价格");
        return false;
      }

      if (!that.handleInsureParam()) {
        //验证
        return;
      }
      Param = that.getDefaultParam();
      Param.data = insureData;
      Param.partnerId = app.partnerId;
      console.log("表单参数", Param);

      T.showLoading();
      api.saveInsure({
        data: Param,
        method: "POST",
        success: function success(result) {
          if (result.code == 0) {
            var data = result.data;
            //var insureNum = data.insureNum || "";
            var encryptInsureNum = data.encryptInsureNum || "";
            wx.navigateTo({
              url: '../pay/pay?id=' + encryptInsureNum
            });
          }
        },
        complete: function complete() {
          T.hideLoading();
        }
      });
    }
  },

  getDefaultParam: function getDefaultParam() {
    var temp = this.data;
    var insurantType; //20-本人，21-他人，22-多人，30-团单   //其中其他人时，被保人关系不能为本人
    if (temp.isToMySelf || temp.isHaveToMyself && this.data.tobeParam.length == 1) {
      //  如果加上了被保人关系是本人  这个isHaveToMyself要赋值
      insurantType = 20;
    } else if (Trial.supportMore()) {
      insurantType = 22;
    } else if (Trial.supportMono()) {
      insurantType = 30;
    } else {
      insurantType = 21;
    }
    return {
      startDate: insureData[102][0].startDate,
      endDate: insureData[102][0].endDate,
      notifyAnswerId: "", //风险评测id
      source: 2, //1:"PC", 2:"H5", 3:"IOS", 4:"ANDROID", 5:"OPENAPI", 6:"CPS&API";
      partnerId: app.partnerId, //渠道标识
      thirdPartyId: "", //第三方id
      productId: opt.productId, //产品id
      productPlanId: opt.planId, //计划id

      price: temp.price, //
      totalNum: this.getBuyCount(), //份数           //

      insureInsurantType: insurantType,
      insureBeneficiaryType: Trial.getInsureBeneficiaryType(), //受益人类型(0没有 1法定,2指定 12指定或者法定)

      ap: false, // ap or cps 投保         //
      trialGenes: Trial.getTrialGenes(), //试算因子

      againSubmit: false,
      autoRenewal: false,
      insureNum: "",
      isInsurantPayment: 0
    };
  },
  getBuyCount: function getBuyCount() {
    if (this.data.isToMySelf) {
      return this.data.buyCount;
    } else {
      var myCount = 0;
      var data = this.data.tobeParam;
      var count;
      for (var i = 0; i < data.length; i++) {
        count = +data[i].buyCount;
        myCount += count;
      }
      return myCount || 1;
    }
  },
  inputBlur: function inputBlur(e) {
    console.log(e);
    var dataset = e.target.dataset;
    var mid = dataset.mid;
    var index = dataset.index || 0;
    var key = dataset.key;
    var value = e.detail.value;
    if (key && mid) {
      this.setInsureData(mid, index, key, value);
    }
  },
  selectChange: function selectChange(e) {
    console.log(e);
    var dataset = e.target.dataset;
    var mid = dataset.mid;
    var key = dataset.key;
    var index = dataset.index || 0;
    var typeid = dataset.typeid;
    this.data.selectedMap[key + mid + index] = e.detail.value || 0;
    var value = e.detail.value;
    this.setData({
      selectedMap: this.data.selectedMap
    });

    if (key == "toWho") {
      this.data.isToMySelf = this.data.toWhoData.values[value].controlValue == 1;
      this.toWhoAction();
      return;
    }
    if (key == "insuranceDate") {
      Trial.setStartDate(T.formatDate("yyyy-MM-dd", value));
      this.data.endDateData.value = T.formatDate("yyyy-MM-dd", Trial.formatInsuranceDate(value));
      this.setData({
        endDateData: this.data.endDateData
      });

      this.resetDateLimit(this.data.modules);
      this.setData({
        dateLimitMap: this.data.dateLimitMap
      });

      this.checkBirthDateLimit();
      return;
    }

    if (key && mid) {
      var attr = moduleMap[mid].attr.default || moduleMap[mid].attr.appoint || moduleMap[mid].attr;
      //var obj = T.getAttrObject(attr,"keyCode",key)[0]||{};
      value = typeid == 1 ? value : attr[key].values[value].controlValue;
      this.setInsureData(mid, index, key, value);
    }
  },
  checkBirthDateLimit: function checkBirthDateLimit() {
    var tData = this.data.isToMySelf ? [tobeBySelfParam] : this.data.tobeParam;
    var tMid = this.data.isToMySelf ? 10 : 20;
    for (var i = 0; i < tData.length; i++) {
      var birth = this.data.isToMySelf ? tobeBySelfParam["birthdate"] : this.data.tobeParam[i] && this.data.tobeParam[i].birthdate;
      if (!birth) {
        continue;
      }
      Trial.checkInput(tMid, 0, "birthdate", birth, tData);
    }
  },
  setInsureData: function setInsureData(mid, index, key, value) {
    if (typeof value == "string") {
      value = value.trim();
    }
    insureData[mid][index] = insureData[mid][index] || {};

    if (insureData[mid][index][key] !== undefined) {
      insureData[mid][index][key] = value;
    }

    if (mid == 10 && tobeBySelfParam[key] !== undefined) {
      tobeBySelfParam[key] = value;
    }

    var flag = Trial.checkInput(mid, index, key, value, insureData);

    if (flag) {
      if (key == "cardNumber" || key == "cardTypeName" || key == "birthdate" || key == "sex") {
        var selectedCardId = insureData[mid][index]["cardTypeName"];
        var cardNumber = insureData[mid][index]["cardNumber"];
        if (selectedCardId == 1) {
          if (key == "cardTypeName") {
            if (!Trial.checkInput(mid, index, "cardNumber", cardNumber, insureData)) {
              return false;
            }
          }
          var birthdate = T.getBirthdateAndSexByCardNumber(cardNumber).birthdate;
          var sex = T.getBirthdateAndSexByCardNumber(cardNumber).sex;
          if (birthdate) {
            this.data.selectedMap["birthdate" + mid + index] = birthdate;
            insureData[mid][index]["birthdate"] = birthdate;

            this.data.selectedMap["sex" + mid + index] = sex;
            insureData[mid][index]["sex"] = sex;

            if (mid == 10) {
              tobeBySelfParam["birthdate"] = birthdate;
              tobeBySelfParam["sex"] = sex;
            }

            this.setData({
              selectedMap: this.data.selectedMap
            });

            if (this.data.isToMySelf && this.ifTobeReady("birthdate") && this.ifTobeReady("sex") && this.ifTobeReady(key)) {
              this.tryInsurantPrice();
            }

            return;
          }
        }
      }

      if (this.data.isToMySelf && this.ifTobeReady(key)) {
        this.tryInsurantPrice();
      }
    }

    console.log("selectedMap....", this.data.selectedMap);
  },
  tryInsurantPrice: function tryInsurantPrice(callback) {
    var that = this;
    isTrying = true;

    var param = this.data.isToMySelf ? [tobeBySelfParam] : this.data.tobeParam;

    param.forEach(function (item, index) {
      //试算的份数和投保的份数传值不同   在兼容份数之后  这里要改成每个被保险人的份数根据自己选择的来
      if (param[index]["buyCount"]) {
        param[index]["buyCount"] = that.data.buyCount;
      }
    });
    Trial.trialInsuredPrice(param, function (err, priceResult) {
      if (err) {
        T.showTips(err.msg || "被保险人价格试算失败");
        T.hideLoading();
      } else {
        console.log("试算被保险人价格结果：", priceResult);
        isTrying = false;
        that.data.price = priceResult.totalPrice;
        that.setData({
          price: that.data.price
        });
        app.globalData.tobeTempData.priceData = priceResult;
        callback && callback();
      }
    }, true);
  },
  ifTobeReady: function ifTobeReady(currentKey) {
    //TODO   要考虑切换给谁投保时的被保险人的数据问题
    currentKey = currentKey || "";
    var data = tobeBySelfParam;
    var needTry = ["sex", "birthdate", "buyCount", "jobText", "haveMedical"];
    var value, flag;
    for (var key in data) {
      if (needTry.indexOf(currentKey) > -1) {
        if (needTry.indexOf(key) < 0) {
          continue;
        }
      }
      value = data[key];
      flag = Trial.checkInput(20, 0, key, value, data);
      if (!flag || value === "" || value == undefined) {
        return false;
      }
    }

    return true;
  },
  gotoDeclare: function gotoDeclare() {
    wx.navigateTo({
      url: '../declare/declare'
    });
  }

});

//0:下拉框
//1:日历控件
//2:下拉框+日历控件
//3:文本框
//4:地区控件
//5:职业控件
//6:密码框
//7:文本
//8:对话框
//9:单选框
//10:复选框 
 			}); 	require("pages/product/insure/insure.js");
 		__wxRoute = 'pages/product/hzins-tips/hzins-tips';__wxRouteBegin = true; 	define("pages/product/hzins-tips/hzins-tips.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

// pages/product/hzins-tips/hzins-tips.js
var app = getApp();
Page({
  data: {
    hzinsTips: []
  },
  onLoad: function onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      hzinsTips: app.globalData.hzinsTips
    });
  },
  onReady: function onReady() {
    // 页面渲染完成
  },
  onShow: function onShow() {
    // 页面显示
  },
  onHide: function onHide() {
    // 页面隐藏
  },
  onUnload: function onUnload() {
    // 页面关闭
  }
}); 
 			}); 	require("pages/product/hzins-tips/hzins-tips.js");
 		__wxRoute = 'pages/product/declare/declare';__wxRouteBegin = true; 	define("pages/product/declare/declare.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

var app = getApp();
var T = require("../../../utils/util");
Page({
  data: {
    insureDeclareContent: ""
  },
  onLoad: function onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
    var content = app.globalData.insureDeclareContent || "暂无内容";
    content = T.htmlToText(content);
    this.setData({
      insureDeclareContent: content
    });
  },
  onReady: function onReady() {
    // 页面渲染完成
  },
  onShow: function onShow() {
    // 页面显示
  },
  onHide: function onHide() {
    // 页面隐藏
  },
  onUnload: function onUnload() {
    // 页面关闭
  }
}); 
 			}); 	require("pages/product/declare/declare.js");
 		__wxRoute = 'pages/product/insure-add/insure-add';__wxRouteBegin = true; 	define("pages/product/insure-add/insure-add.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

var Trial = require("../../../utils/trial-core");
var T = require("../../../utils/util");
var app = getApp();
var tobeTempData;
var opt;
var tempParam;
Page({
  data: {
    index: 0,
    config: {},
    tobeData: {},
    tobeParam: [],
    applicantParam: {},
    selectedMap: {},
    isAdd: true
  },
  onLoad: function onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
    opt = options || {};
    tempParam = {};

    app.globalData.tobeTempData = app.globalData.tobeTempData || {};
    tobeTempData = app.globalData.tobeTempData;
    tobeTempData.tobeParam = tobeTempData.tobeParam || [];
    tobeTempData.selectedMapArr = tobeTempData.selectedMapArr || [];

    opt.index = opt.index === undefined ? tobeTempData.tobeParam.length : opt.index;

    this.initParam();

    this.setData({
      index: opt.index,
      config: tobeTempData.config,
      tobeData: tobeTempData.tobeData,
      tobeParam: tobeTempData.tobeParam,
      applicantParam: tobeTempData.applicantParam || {},
      selectedMap: tobeTempData.selectedMapArr[opt.index] || {},
      isAdd: opt.index === tobeTempData.tobeParam.length
    });

    console.log("tobeTempData", tobeTempData, "onLoad...");
    console.log("tempParam", tempParam, "onLoad...");
    console.log("opt", opt, "onLoad...");
    console.log("selectedMap", this.data.selectedMap, "onLoad...");
  },
  onReady: function onReady() {
    // 页面渲染完成
  },
  onShow: function onShow() {
    // 页面显示
  },
  onHide: function onHide() {
    // 页面隐藏
  },
  onUnload: function onUnload() {
    // 页面关闭
  },
  addTobe: function addTobe() {
    var flag = this.checkTobeParam();
    var that = this;
    if (flag) {
      tobeTempData.tobeParam[opt.index] = T.extend({}, tempParam);
      this.tryInsuredPrice(function (priceResult) {
        app.globalData.tobeTempData.priceData = priceResult;
        tobeTempData.tobeParam[opt.index].price = priceResult.priceList[opt.index];

        tobeTempData.selectedMapArr[opt.index] = that.data.selectedMap;

        wx.navigateBack({
          delta: 1
        });
      });
    }
  },
  checkTobeParam: function checkTobeParam() {
    var value, flag;
    for (var key in tempParam) {
      value = tempParam[key];

      if (!this.checkOtherParam(key, value)) {
        return false;
      }
      var flag = Trial.checkInput(20, opt.index, key, value, tempParam, true);
      if (!flag) {
        return false;
      }
    }

    tempParam.buyCount = Trial.getBuyCountData().default || 1;
    console.log(tempParam);
    return true;
  },
  checkOtherParam: function checkOtherParam(key, value) {
    if (key == "cardNumber") {
      if (value && value == this.data.applicantParam.cardNumber && tempParam.relationInsureInsurant != 1) {
        T.showTips("被保险人证件号码不能和投保人一致");
        return false;
      }

      var cardNumbers = T.pluck(this.data.tobeParam, "cardNumber") || [];
      var temp = T.clone(cardNumbers);
      temp.splice(+opt.index, 1);
      if (value && temp.indexOf(value) > -1) {
        T.showTips("被保险人证件号码重复");
        return false;
      }
    }
    return true;
  },
  initParam: function initParam() {
    var item;
    var attr = tobeTempData.tobeData.attr.default;
    for (var key in attr) {
      item = attr[key];
      tempParam[item.keyCode] = item.value = tobeTempData.tobeParam[opt.index] && tobeTempData.tobeParam[opt.index][item.keyCode] || "";

      if (item.type == 1) {
        //日历控件
        var limit = Trial.calculateDateLimit({
          mid: tobeTempData.tobeData.id,
          key: item.keyCode
        });

        item.start = T.formatDate("yyyy-MM-dd", limit.minDate);
        item.end = T.formatDate("yyyy-MM-dd", limit.maxDate);
        item.default = item.start;
        if (item.keyCode == "birthdate") {
          item.default = ""; //item.end;
        }
        tempParam[item.keyCode] = tempParam[item.keyCode] || item.default;
        console.log(item.keyCode + "日期范围", item.start, item.end);
      }

      if (item.keyCode == "relationInsureInsurant") {
        item.values = this.diyFilterList(item.values); //把本人这个关系去掉
      }

      if (item.values) {//约束——先不处理
        //item.values = Trial.procRestricts(item.values, item.restricts || []) || [];
      }
      if (item.values && item.values.length) {
        tempParam[item.keyCode] = tempParam[item.keyCode] || item.values[0].controlValue;
      }
    }
  },

  tryInsuredPrice: function tryInsuredPrice(cb) {
    Trial.trialInsuredPrice(tobeTempData.tobeParam, function (err, priceResult) {
      console.log("试算后", tobeTempData.tobeParam);
      if (err) {
        T.showTips(err.msg || "被保险人价格试算失败");
      } else {
        console.log("试算被保险人价格结果：", priceResult);
        cb && cb(priceResult);
      }
    });
  },
  diyFilterList: function diyFilterList(data) {
    for (var i = 0; i < data.length; i++) {
      if (data[i].value == "本人") {
        data.splice(i, 1);
        return data;
      }
    }
    return data;
  },
  inputBlur: function inputBlur(e) {
    var dataset = e.target.dataset;
    var mid = dataset.mid;
    var index = dataset.index || 0;
    var key = dataset.key;
    var value = e.detail.value;
    if (key && mid) {
      this.setInsureData(key, value);
    }
  },
  selectChange: function selectChange(e) {
    console.log(e);
    var dataset = e.target.dataset;
    var mid = dataset.mid;
    var key = dataset.key;
    var index = dataset.index || 0;
    var typeid = dataset.typeid;
    this.data.selectedMap[key + mid + index] = e.detail.value || 0;
    var value = e.detail.value;
    this.setData({
      selectedMap: this.data.selectedMap
    });
    if (key && mid) {
      var attr = this.data.tobeData.attr.default;
      value = typeid == 1 ? value : attr[key].values[value].controlValue;
      this.setInsureData(key, value);
    }
  },
  setInsureData: function setInsureData(key, value) {
    if (typeof value == "string") {
      value = value.trim();
    }
    tempParam[key] = value;

    var flag = Trial.checkInput(20, opt.index, key, value, tempParam);
    if (!this.checkOtherParam(key, value)) {
      flag = false;
    }

    if (flag) {
      if (key == "cardNumber" || key == "cardTypeName" || key == "birthdate" || key == "sex") {
        var selectedCardId = tempParam["cardTypeName"];
        var cardNumber = tempParam["cardNumber"];
        if (selectedCardId == 1) {
          var birthdate = T.getBirthdateAndSexByCardNumber(cardNumber).birthdate || "";
          var sex = T.getBirthdateAndSexByCardNumber(cardNumber).sex;
          if (birthdate) {
            this.data.selectedMap["birthdate" + "20" + opt.index] = birthdate;
            tempParam["birthdate"] = birthdate;

            this.data.selectedMap["sex" + "20" + opt.index] = sex;
            tempParam["sex"] = sex;

            this.setData({
              selectedMap: this.data.selectedMap
            });
          }
        }
      }
    }
  }
}); 
 			}); 	require("pages/product/insure-add/insure-add.js");
 		__wxRoute = 'pages/product/pay/pay';__wxRouteBegin = true; 	define("pages/product/pay/pay.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

var _ = require('../../../utils/underscore');
var moment = require("../../../utils/moment");
var api = require('../../../utils/api.js');
var utils = require('../../../utils/util.js');
var App = getApp();

Page({
  data: {
    windowWidth: App.systemInfo.windowWidth,
    windowHeight: App.systemInfo.windowHeight,
    loading: false,
    firstLoading: true,
    order: {}
  },
  onLoad: function onLoad(opt) {
    var self = this;
    var payState = App.payState;
    utils.showLoading();
    this.setData({
      encryptInsureNum: opt.id
    });
    api.getOrderDetail({
      data: { encryptInsureNum: self.data.encryptInsureNum },
      success: function success(result) {
        self.setData({ firstLoading: false });
        utils.hideLoading();
        var item = result.data;
        item.isEffect = new Date(item.startDate.replace(/-/g, '/') || '') <= new Date() ? true : false;
        if (item.createTime.substr(0, 10) == moment(new Date()).format('YYYY-MM-DD')) {
          item.isEffect = new Date(item.startDate.replace(/-/g, '/'), " 23:30:00") < new Date() ? true : false;
        }
        self.setData({
          order: _.extend(item, { createTime: moment(item.createTime).format('YYYY-MM-DD HH:mm'), payAmountStr: (item.payAmount / 100).toFixed(2) })
        });
        console.log(self.data.order, "aaaaaaaaaa");
      }
    });
  },
  paying: function paying() {
    var self = this;
    var bool = self.data.loading;
    if (!bool) {
      self.setData({
        loading: true
      });
      api.paying({
        data: {
          gatewayMoney: self.data.order.payAmount,
          insureNum: self.data.encryptInsureNum,
          partnerId: App.partnerId
        },
        success: function success(result) {
          wx.requestPayment({
            'timeStamp': result.data.gatewayData.timeStamp,
            'nonceStr': result.data.gatewayData.nonceStr,
            'package': result.data.gatewayData.package,
            'signType': result.data.gatewayData.signType,
            'paySign': result.data.gatewayData.paySign,
            'success': function success(res) {
              self.setData({
                loading: false
              });
              wx.redirectTo({
                url: '/pages/product/success/success?id=' + self.data.encryptInsureNum
              });
            },
            'fail': function fail(res) {
              self.setData({
                loading: false
              });
              console.log(res);
            }
          });
        },
        complete: function complete() {
          self.setData({
            loading: false
          });
        }
      });
    }
  }
}); 
 			}); 	require("pages/product/pay/pay.js");
 		__wxRoute = 'pages/product/success/success';__wxRouteBegin = true; 	define("pages/product/success/success.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

Page({
  data: {
    id: ""
  },
  onLoad: function onLoad(opt) {
    this.setData({
      id: opt.id || ""
    });

    wx.setNavigationBarTitle({
      title: '支付成功'
    });
  },
  toHome: function toHome() {
    wx.switchTab({
      url: '/pages/home/home'
    });
  }
}); 
 			}); 	require("pages/product/success/success.js");
 		__wxRoute = 'pages/product/my-detail/my-detail';__wxRouteBegin = true; 	define("pages/product/my-detail/my-detail.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

// pages/product/my-detail/my-detail.js
Page({
  data: {},
  onLoad: function onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady: function onReady() {
    // 页面渲染完成
  },
  onShow: function onShow() {
    // 页面显示
  },
  onHide: function onHide() {
    // 页面隐藏
  },
  onUnload: function onUnload() {
    // 页面关闭
  }
}); 
 			}); 	require("pages/product/my-detail/my-detail.js");
 		__wxRoute = 'pages/product/my-insure/my-insure';__wxRouteBegin = true; 	define("pages/product/my-insure/my-insure.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

// pages/product/my-insure/my-insure.js
Page({
  data: {},
  onLoad: function onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady: function onReady() {
    // 页面渲染完成
  },
  onShow: function onShow() {
    // 页面显示
  },
  onHide: function onHide() {
    // 页面隐藏
  },
  onUnload: function onUnload() {
    // 页面关闭
  }
}); 
 			}); 	require("pages/product/my-insure/my-insure.js");
 		__wxRoute = 'pages/my/main/main';__wxRouteBegin = true; 	define("pages/my/main/main.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

//index.js
//获取应用实例
var app = getApp();
Page({
  data: {
    userInfo: {},
    showShare: false
  },
  //事件处理函数
  bindViewTap: function bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    });
  },
  switchShare: function switchShare(e) {
    var flag = e.currentTarget.dataset.flag == "1";
    this.setData({
      showShare: flag
    });
  },
  onShareAppMessage: function onShareAppMessage() {
    return {
      title: '微金保--随时随地买保险',
      desc: '微金保--随时随地买保险',
      path: 'pages/home/home?partnerId=' + app.partnerId
    };
  },
  onLoad: function onLoad() {

    var that = this;
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function (userInfo) {
      //更新数据
      that.setData({
        userInfo: userInfo
      });
    });

    wx.setNavigationBarTitle({
      title: '我的账户'
    });
  },
  //打电话
  tel: function tel(ev) {
    wx.makePhoneCall({
      phoneNumber: ev.currentTarget.dataset.tel
    });
  },
  //导航
  goTo: function goTo(ev) {
    var url = ev.currentTarget.dataset.url;

    wx.navigateTo({
      url: '/pages/my/' + url + '/' + url
    });
  }
}); 
 			}); 	require("pages/my/main/main.js");
 		__wxRoute = 'pages/my/claim/claim';__wxRouteBegin = true; 	define("pages/my/claim/claim.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 "use strict";

// pages/my/claim/claim.js
Page({
  data: {},
  onLoad: function onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady: function onReady() {
    // 页面渲染完成
  },
  onShow: function onShow() {
    // 页面显示
  },
  onHide: function onHide() {
    // 页面隐藏
  },
  onUnload: function onUnload() {
    // 页面关闭
  }
}); 
 			}); 	require("pages/my/claim/claim.js");
 		__wxRoute = 'pages/my/faq/faq';__wxRouteBegin = true; 	define("pages/my/faq/faq.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

// pages/my/faq/faq.js
Page({
  data: {
    showAll: true,
    list: [{
      title: "购买前的问题",
      data: [{
        title: '1、如何进行购买？',
        content: ['本保险频道的所有产品均支持在线投保，首先点选要投保的产品，然后填写真实的投保信息，最后在线完成保费支付即可完成投保，支付完成电子保单自动发送至您投保时填写的邮箱，方便快捷。']
      }, {
        title: '2、购买需要准备什么资料？在投保前您需要准备齐全以下资料：',
        content: ['1）投保人、被保险人的姓名、证件号码（身份证、护照、出生证等证件号码）。', ' 2）一个您经常使用的电子邮箱，建议使用163、qq等常用邮箱；', '3）直接使用微信支付即可完成在线支付']
      }, {
        title: '3、没有身份证号码可否购买？',
        content: ['如果没有身份证号码可以使用护照、出生证等证件号码投保，但需要填写出生日期，在投保的时候证件类型选择其他即可。']
      }, {
        title: '4、电子保单是否具有法律效力，理赔时保险公司承认么？',
        content: ['电子保单上的信息均是实时进入保险公司核心承保系统的，投保完成后所有的电子保单均可以在拨打保险公司电话验真，电子保单具有与纸质保单同等的法律效力，出险后提供电子保单号码及必要的资料资料即可获得理赔。']
      }]
    }, {
      title: "投保中的问题",
      data: [{
        title: '1、投保人和被保险人有什么区别，该如何填写？',
        content: ['投保人是受被保险人委托，进行投保操作的成年人，投保人需具备民事行为能力，投保人和被保险人可以为同一人，也可以不为同一人。在投保页面，投保人信息栏填写投保人信息，被保险人信息栏填写需要保险保障的人的信息。']
      }, {
        title: '2、保险期限该如何选择？',
        content: ['在产品展示页面，选择您要保障的保险期限，比如出游7天，那么在您要投保的产品页面选择7天即可']
      }, {
        title: '3、当日生效是什么意思？',
        content: ['当日生效是指在您填写完投保信息，并支付完成两个小时后保单产生效力，特别注意，保单是在您支付完成一小时后生效，比如您今天10点的户外出行活动，最好在8点前完成支付。']
      }, {
        title: '4、如何选择支付方式？',
        content: ['在您投保完成后，点击“立即支付”即可进入微信的在线支付页面完成后续支付行为。']
      }, {
        title: '5、支付不成功该怎么办？',
        content: ['如果支付不成功，有可能是您的微信钱包中余额不足，可进行充值或者重新绑定其他银行卡，如仍未成功，您可以联系在线客服或者拨打4006-788-169获得支付指导。']
      }, {
        title: '6、境外旅游保险的英文名该如何填写？',
        content: ['按照护照上的英文名填写即可，投保境外旅游险建议证件号码均选择护照。']
      }]
    }, {
      title: "购买后的问题",
      data: [{
        title: '1、邮箱中没有收到电子保单该怎么办？',
        content: ['投保完成后系统会自动将电子保单发送至您的邮箱，如果您投保时填写的邮箱没有收到电子保单，您可以在本频道的首页“保单查询”中输入“投保人证件号码、投保时填写的邮箱”找到您投保成功的保单，然后在线下载即可。']
      }, {
        title: '2、保单如何查询验真？',
        content: ['您可以拨打保单所属的保险公司的客服电话，提供保单号、投保人姓名、证件号码进行验真']
      }, {
        title: '3、电子保单无法打开怎么办？',
        content: ['电子保单是PDF格式的，如果打不开，有可能是您的电脑没有安装PDF软件或者PDF软件版本过低，建议您下载最新的PDF软件安转后即可打开。']
      }, {
        title: '4、我使用保险办理申根签证该怎么办？',
        content: ['您需要将电子保单彩色打印，将彩打的保单递交使馆即可办理签证。']
      }, {
        title: '5、我拒签了该如何办理？',
        content: ['如保单未生效，拒签可以全退，如果保单已生效需扣除短期保费，如拒签办理退保，请联系在线客服或者拨打4006-788-169客服电话。']
      }, {
        title: '6、退保及变更',
        content: ['意外险、境内旅游险均不支持变更、退保，签证保险拒签并提供拒签证明资料的前提下可办理退保。']
      }]
    }]
  },
  onLoad: function onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady: function onReady() {
    // 页面渲染完成
  },
  onShow: function onShow() {
    // 页面显示
  },
  onHide: function onHide() {
    // 页面隐藏
  },
  onUnload: function onUnload() {
    // 页面关闭
  },
  showAll: function showAll() {
    this.setData({
      showAll: false
    });
  }
}); 
 			}); 	require("pages/my/faq/faq.js");
 		__wxRoute = 'pages/my/insure/insure';__wxRouteBegin = true; 	define("pages/my/insure/insure.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

// pages/my/insure/insure.js
Page({
  data: {},
  onLoad: function onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
    wx.setNavigationBarTitle({
      title: '常用投保人'
    });
  },
  onReady: function onReady() {
    // 页面渲染完成
  },
  onShow: function onShow() {
    // 页面显示
  },
  onHide: function onHide() {
    // 页面隐藏
  },
  onUnload: function onUnload() {
    // 页面关闭
  },
  goTo: function goTo() {
    wx.navigateTo({
      url: '/pages/my/add-insure/add-insure'
    });
  }
}); 
 			}); 	require("pages/my/insure/insure.js");
 		__wxRoute = 'pages/my/add-insure/add-insure';__wxRouteBegin = true; 	define("pages/my/add-insure/add-insure.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

// pages/my/insure/insure.js

Page({
  data: {
    tag: '',
    name: '',
    code: '',
    date: '',
    startDate: '',
    index: 0,
    cardTypeArray: ['身份证', '出生证', '毕业证']
  },
  onLoad: function onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
    var date = new Date();
    this.setData({
      startDate: date.getFullYear() + '-' + date.getMonth() + 1 + '-' + date.getDate()
    });
  },
  onReady: function onReady() {
    // 页面渲染完成
  },
  onShow: function onShow() {
    // 页面显示
  },
  onHide: function onHide() {
    // 页面隐藏
  },
  onUnload: function onUnload() {
    // 页面关闭
  },
  validateHandle: function validateHandle() {},
  bindPickerChange: function bindPickerChange(ev) {
    this.setData({
      index: ev.detail.value
    });
  },
  bindDateChange: function bindDateChange(ev) {
    this.setData({
      date: ev.detail.value
    });
  },
  changeTag: function changeTag(ev) {

    this.setData({
      tag: ev.currentTarget.dataset.tag
    });
  },
  formSubmit: function formSubmit(ev) {
    console.log(ev);
    wx.navigateTo({
      url: "/pages/my/insure/insure"
    });
  },
  formReset: function formReset(ev) {}
}); 
 			}); 	require("pages/my/add-insure/add-insure.js");
 		__wxRoute = 'pages/dispatch';__wxRouteBegin = true; 	define("pages/dispatch.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,XMLHttpRequest,WebSocket,Reporter,webkit,WeixinJSCore){ 			
 'use strict';

var App = getApp();
var api = require('../utils/api.js');
var util = require('../utils/util.js');

Page({
  onLoad: function onLoad(options) {
    var path = options.path ? options.path : '';
    var params = options.params ? options.params.replace(/\*/g, '&').replace(/\-/g, '=') : '';

    if (path == 'home') {
      wx.redirectTo({
        url: '/pages/home/home'
      });
    } else if (path == 'detail') {
      wx.redirectTo({
        url: '/pages/product/detail/detail?' + params
      });
    } else if (path == 'insure') {
      App.globalData.trialGenes = '';
      wx.redirectTo({
        url: '/pages/product/insure/insure?' + params
      });
    } else {
      wx.redirectTo({
        url: '/pages/home/home'
      });
    }
  }
}); 
 			}); 	require("pages/dispatch.js");
 	